Skip to content

Subprocesses

Many neuroimaging analysis functions are implemented as a command line tools that follows the traditional Unix philosphy "does one thing and does it well". The subprocess module makes running these command line tools simple.

import subprocess

Running a subprocess

A simple way to run a subprocess is with subprocess.check_output. The first argument should be your command and the second argument should be shell=True

output = subprocess.check_output('ls -la', shell=True)

print(output.decode())

string.decode()

Python 3 does not assume a character encoding for content read in from files or generated by a subprocess. You are responsible for calling .decode() with the correct character encoding. By default, the character encoding is assumed to be UTF-8, which is backward compatible with ASCII.

Handling errors

If a subprocess fails, you'll receive a subprocess.CalledProcessError. An unhandled exception will typically crash your program. However, if you want to catch the error and handle it in a special way, you can wrap the function call in a try statement

try:
    output = subprocess.check_output('ls -z', shell=True)
except subprocess.CalledProcessError as e:
    print(e.returncode)