Main Content

Running an operating system command from your Python program - the new way with the subprocess module

Archive - Originally posted on "The Horse's Mouth" - 2015-03-06 17:02:04 - Graham Ellis

Python's subprocess module has replaced a series of other modules, and if you're writing new code which calls operating system commands you should use this module in perferance to the older stuff. Easy examples at [here].

The "interesting bit" in various languages is not so much how you cal other commands and languages, but how you handle their inputs and outputs. Here are some subprocess examples:

Running a subprocess, output to file:

  stuff = open("demodata.txt","w")
  subprocess.Popen(["ls","-lat","/etc"],stdout=stuff)


Running a subprocess, output back to your Python script:

  proc = subprocess.Popen(["ls","-lat","/usr"],stdout=subprocess.PIPE)
  while True:
    record = proc.stdout.readline()
    if not record: break
    print record,
  proc.wait()


And you can handle stdin and stderr using exactly the same approach.

Older examples [here] and [here] (that latter showing polymorphism where you can read from a process or from a file in the same example!)