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')

1 comment so far ↓

#1 Maksim on 08.05.09 at 6:47 pm

Have you investigates pyprocessing module? It makes this type of interaction much more robust

Leave a Comment