Pass Subprocess Arguments without Shell Interpolation
Core idea
subprocess.run starts a process and returns CompletedProcess. Pass a fixed executable and a list of argument strings with shell=False, the default. capture_output=True collects stdout and stderr; text=True decodes streams. Set timeout and check the return code.
import subprocess, sysr = subprocess.run([sys.executable, "-I", "-c", "import sys; print(sys.argv[1])", "two words"], capture_output=True, text=True, timeout=5, check=True)print(r.stdout.strip())The fixed child receives one argument containing a space. The child program is trusted and constant.
Inspect an unsuccessful result
import subprocess, sysr = subprocess.run([sys.executable, "-I", "-c", "raise SystemExit(4)"], capture_output=True, timeout=5)print(r.returncode)Without check=True a nonzero exit is available in returncode.
Common mistake
A list avoids ordinary shell interpolation but is not a sandbox: validate arguments against the target program, avoid untrusted executables, and do not insert input into child source code. Windows batch files have special shell behavior. Limit captured output for unbounded children.
Practice
Run the fixed Python child with a different ordinary text argument and verify stdout and returncode; only run locally where process creation is permitted.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Subprocess contracts
Check your understanding of subprocess boundaries.
What is printed?
import subprocess,sysr=subprocess.run([sys.executable,"-I","-c","print(7)"],capture_output=True,text=True,timeout=5)print(r.stdout.strip())What is printed?
import subprocess,sysr=subprocess.run([sys.executable,"-I","-c","raise SystemExit(3)"],timeout=5)print(r.returncode)Which approach avoids ordinary shell interpolation?
What does check=True do for a nonzero exit?