Anna Syme

Click name ↑ to return to homepage

Python subprocess

Use subprocess module to run other programs

import subprocess
subprocess.run(['ls'])
cmd=['ls']
subprocess.run(cmd)

Save the subprocess output

cmd=['ls']
proc1 = subprocess.run(cmd, stdout=subprocess.PIPE)
print(proc1.stdout)

Save the subprocess output into a file

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

Pipe output to another subprocess

cmd1 = ['ls'] #list my files
cmd2 = ['wc', '-l'] #count number of lines
f = open("numlines.txt", "w")
proc1 = subprocess.run(cmd1, stdout=subprocess.PIPE)
proc2 = subprocess.run(cmd2, 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 please.sh") # runs please.sh with bash
os.system("python chips.py") # runs chips.py with python