Subprocess arguments
Keep untrusted data out of code and shell parsing.
On this page
The concept
Text supplied by a user is data, not an instruction to execute. Parse integers with int and structured data with json.loads. eval, exec, and untrusted pickle loading can execute code and are inappropriate substitutes for ordinary parsing.
subprocess.run accepts an argument list so the shell does not need to parse a concatenated command string. The example runs a fixed expression using the current Python interpreter, captures output, checks failure, and limits runtime. No user input is inserted into the code passed to -c. For tokens, use secrets rather than simulation-oriented random.
Worked example
Extract the example files. From the python_from_zero directory, run the following command in a terminal. On Windows, use py in place of python3.
python3 08_professional_workflow/66_security_boundaries/lesson.pyimport subprocess
import sys
result = subprocess.run(
[sys.executable, "-c", "print(6 * 7)"], capture_output=True, text=True, check=True, timeout=5
)
print("Subprocess result:", result.stdout.strip())Trace the result
- sys.executable selects the same interpreter used for the current program.
- The argument list is passed directly without shell=True.
- check=True rejects nonzero exits and timeout limits waiting; the captured output is then displayed.
Subprocess result: 42Line-by-line walkthrough
Line 1: import subprocess
Load subprocess (running a child process with controlled arguments). Importing makes these names available; it is not a call to every function in the module.
Line 2: import sys
Load sys (interpreter information and command-line arguments). Importing makes these names available; it is not a call to every function in the module.
Lines 4–6: result = subprocess.run(
Evaluate subprocess.run([sys.executable, '-c', 'print(6 * 7)'], capture_output=True, text=True, check=True, timeout=5), then bind or update result with the result. The call finishes before its return value is bound; a failed call does not produce a successful assignment. Assignment itself does not imply a deep copy.
Line 7: print("Subprocess result:", result.stdout.strip())
Evaluate the print arguments from the current state and display them. sep controls separators and end controls the ending when those options are provided. Displaying a value does not return that value from the surrounding function.
Common mistake
Building a shell command by concatenating input with shell=True can turn data into instructions. Avoid that design.