Glossary

Subprocess

The subprocess module provides the standard way to spawn external processes from Python, send them input, capture their output, and check their exit codes. The primary function is subprocess.run() (Python 3.5+), which runs a command, waits for it to complete, and returns a CompletedProcess object containing the return code, stdout, and stderr.

Common usage patterns: subprocess.run(["ls", "-la"], capture_output=True, text=True) runs a command and captures its output as a string; subprocess.run(["git", "status"], check=True) raises CalledProcessError if the command fails; subprocess.run("echo hello | wc", shell=True) runs a shell pipeline (use shell=True only when necessary, as it introduces security risks with untrusted input).

For more complex interactions — reading output incrementally, sending input, managing long-running processes — use subprocess.Popen, which provides lower-level control. Popen supports stdin, stdout, and stderr pipes, process polling, and killing. The subprocess module replaces the older os.system(), os.popen(), and commands module, all of which are considered deprecated for new code.

Related terms: Module

Discussed in:

This site is currently in Beta. Please email Chris Paton (cpaton@gmail.com) with any suggestions, questions or comments.