Python subprocess quick and dirty

11 March 2019

Many shell programs can be controlled entirely with arguments and piping data in. Let’s say you are trying to do something in Python which a program will already do for you; it would be great if there was an easy way to face off the shell.

Thankfully subprocess can be used for this. Below is an example which uses echo to generate output on stdout which is then used as stdin for cat.

import subprocess

echoproc = subprocess.Popen(['echo', 'echo is sending this text to stdout'], \
                             stdout=subprocess.PIPE)

catproc = subprocess.Popen(['cat'], \
                             stdin=echoproc.stdout, \
                             stdout=subprocess.PIPE, \
                             stderr=subprocess.PIPE)

stdout, stderr = catproc.communicate()

print(b"stdout: " + stdout)
print(b"stderr: " + stderr)

Note that stdout and stderr are a bytes type (rather than str)