Friday, December 28, 2007

fun with python: running unix command with commands module

One of the best thing in python is, the fact that it have a "battery included", this I really believe.

There is a few ways of running system command on python. There is the popular, execl, execlv, etc in the os modules, which is cross platform.

There is also a commands module. What is cool about it, is that, it will generate output. Where as execl, will exit python shell, back to the parent shell. Meaning, it's easy to write code that read an output of a command, and put it in a front end of something. While it is cool, the command module comes with a cost, it's only available for unix like system, such as linux, bsd, and other unix.

Here's an example, assumes that you already started python, in python shell, either in terminal, or idle, type

>>> import commands

this will loads the modules, now type

>>> commands.getstatusoutput('ls /')

you should get something like this:
(0, 'bin\nboot\ncdrom\ndebian\ndev\netc\nhome\ninitrd\ninitrd.img\nlib\nlib32\nlib64\nlost+found\nmedia\nmnt\nopt\nproc\nroot\nsbin\nsrv\nsys\ntmp\nusr\nvar\nvmlinuz')
the output depends on the system you have. the first part of the tuple is the exit code, which since the code successfully executed, it's 0. the second part is the output of the command, separated by \n.

Now type

>>> commands.getoutput('ls /')

you should get something like this
the output differs between system. now you get a string again separated by \n.

last methods that is available to the commands module is. getstatus, this can only run on an directory:


the output should be something like this.
'drwxr-xr-x 23 root root 4096 2007-12-11 13:21 /'
What's interesting is, it getoutput, and getstatusoutput, applies to many system command(if not all).

interesting example that I do. This is to print the result of ping, interesting example

import commands
s=commands.getoutput('ping -c 10')
#i try to limit the command to make sure it stops
l=s.split('\n') #because it's separated by \n
for line in l:
print l

another interesting thing to do is, is to get cpu info, nothing that cannot be done, using open, since it uses the proc filesystem(gotta love /proc) but still it's interesting.

import commands
s=commands.getoutput('cat /proc/cpuinfo)
for line in s.split('\n'):
print line

the commands module is an interesting way to automate stuff on unix. Pity it doesn't work, on windows. But still it's fun, and interesting. Something the original unix principle.

No comments:

Post a Comment