all Python 3subprocessterm
subprocess
module
Run external programs: pass arguments, get the exit code, capture stdout and stderr.
Syntax
import subprocess
subprocess.run is almost always enough; Popen is for talking to a process while it runs. Pass the command as a list of arguments — shell=True with a string built from user input opens command injection. A non-zero exit code is not an error by itself: you get an exception only with check=True. The module replaces os.system and os.popen.
Examples
import subprocess, sys
r = subprocess.run([sys.executable, '-c', 'print("hi")'], capture_output=True, text=True)
print(r.returncode, r.stdout.strip()) # → 0 hi
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy