Anna Syme

Click name ↑ to return to homepage

Python subprocess

Use subprocess module to run other programs

import subprocess['ls'])

Save the subprocess output

proc1 =, stdout=subprocess.PIPE)

Save the subprocess output into a file

f = open("output.txt", "w") # this creates the file
cmd=['ls'], stdout=f) # this sends it to f
with open("output.txt", "r") as f:

Pipe output to another subprocess

cmd1 = ['ls'] #list my files
cmd2 = ['wc', '-l'] #count number of lines
f = open("numlines.txt", "w")
proc1 =, stdout=subprocess.PIPE)
proc2 =, input=proc1.stdout, stdout=f)

The older way - os module

import os
os.system('echo this is os system') # runs the echo comnmand
os.system("bash") # runs with bash
os.system("python") # runs with python