Wednesday 12 September 2012

How to run shell commands in python

How to run shell commands in python

Inorder to run your shell commands in python script, you may need to import an module named os. Below is the simple example on how it actually works

import os
os.system('ls -l /boot/')
total 22784
-rw-r--r-- 1 root root 791023 Apr 11 05:56 abi-3.2.0-23-generic
-rw-r--r-- 1 root root 140279 Apr 11 05:56 config-3.2.0-23-generic
drwxr-xr-x 3 root root 12288 Aug 14 18:51 grub
-rw-r--r-- 1 root root 14163334 Aug 14 18:51 initrd.img-3.2.0-23-generic
-rw-r--r-- 1 root root 176764 Nov 27 2011 memtest86+.bin
-rw-r--r-- 1 root root 178944 Nov 27 2011 memtest86+_multiboot.bin
-rw------- 1 root root 2884358 Apr 11 05:56 System.map-3.2.0-23-generic
-rw-r--r-- 1 root root 4965840 Apr 25 21:41 vmlinuz-3.2.0-23-generic

In the above example, we listed the files on /boot folder by importing an os module and its execution can be done by running the system method with os object. Below is an another example for your reference, and it shows how to execute free command to know the ram usage.

os.system('free -m')
total used free shared buffers cached
Mem: 1934 1618 316 0 119 769
-/+ buffers/cache: 728 1205
Swap: 1905 0 1905 0

The above can also be done with other modules such as commands and os.popen, which will be discussed on the following articles.



No comments:

Post a Comment