Scrawls from Preston...

Powered by Pelican.

Tue 14 July 2009

calling to the shell in python

This is one of the most frequent utility routines I have in many (most?) of my python scripts. Creating subprocesses in python is very flexble and powerful, but a bit verbose. Sometimes you just want to run a command and set a variable to the output.

from subprocess import Popen, call, STDOUT, PIPE

def sh(cmd):

return Popen(cmd,shell=True,stdout=PIPE,stderr=PIPE).communicate()[0]

You can then just use this as:

sh('ps -x')