Main Content

Running operating system commands from your Python program

Archive - Originally posted on "The Horse's Mouth" - 2010-05-14 12:33:29 - Graham Ellis

As from Python 2.6, os.popen and friends are deprecated methods and you should use the subprocess module for subprocesses. So that's the way to go if you want to run operating system commands. New example showing this - [here]

Starting with:
from subprocess import *

I can run a process and allow its output to to stdout via the call utility:

stuff0 = call("ls")

I can run a process and capture its output to a variable (2 examples):

stuff1 = Popen(["ls"], stdout=PIPE).communicate()[0]
stuff2 = Popen(["ls","-l"], stdout=PIPE).communicate()[0]


And I can open a process that I can then read back from it (2 more examples):

pingalong = Popen("ping -q -c2 192.168.200.134", shell=True, stdout=PIPE).stdout
pingalot = Popen(["ping","-q","-c2","192.168.200.115"], stdout=PIPE).stdout


Note the use of shell=True to push the incoming command through the shell, rather than have to split up the command and parameters yourself.