Sub topic 3
Avoiding Shell Injection with Python `subprocess`
Assume you know basic Python exceptions, terminal commands, standard input and output, and the difference between text and bytes. This chapter focuses on safe process control and on cases where subprocess.run() is not enough.
Pass Arguments as a List
Shell injection happens when untrusted text is interpreted as shell syntax. A filename such as report.txt; echo hacked could become two commands if passed through a shell.
Pass each argument as a separate list item. Python then sends the value directly to the program.
import subprocess
filename = "report.txt; echo hacked"
subprocess.run(["cat", filename], check=True)Avoid shell=True for values that come from users, files, or network requests. shlex.split() can split a trusted command string into arguments, but it does not make an untrusted command safe.
Use `Popen` for Long-Running Processes
subprocess.run() waits for completion. subprocess.Popen gives you a process object that you can poll, wait for, or communicate with while the child runs.
Stream Output as It Arrives
import subprocess
import sys
with subprocess.Popen(
[sys.executable, "-u", "-c", "for i in range(3): print(i)"],
stdout=subprocess.PIPE,
text=True,
) as process:
for line in process.stdout:
print("received:", line.rstrip())
print("exit code:", process.returncode)The -u option disables buffering in this example, so output becomes visible promptly.
Connect Processes in a Pipeline
Connect one process's standard output to another process's standard input. Close the parent's copy of the pipe so the consumer can receive end-of-file.
import subprocess
import sys
producer = subprocess.Popen(
[sys.executable, "-c", "print('a b c')"],
stdout=subprocess.PIPE,
)
consumer = subprocess.Popen(
[sys.executable, "-c", "import sys; print(len(sys.stdin.read().split()))"],
stdin=producer.stdout,
stdout=subprocess.PIPE,
text=True,
)
producer.stdout.close()
output, _ = consumer.communicate()
producer.wait()
print(output.strip())Avoid Pipe Deadlocks
A pipe has a limited buffer. If a child writes enough data while the parent waits without reading, both processes can block. Use communicate() when you need complete output, or continuously read streams as they arrive. Do not call wait() before draining a piped stream.
Account for Operating Systems
Executable names, quoting rules, shell commands, and default encodings differ across Windows, macOS, and Linux. Use sys.executable for the current Python interpreter, pathlib.Path for paths, and argument lists instead of platform-specific command strings. Test commands on every supported operating system.
Asynchronous Subprocesses
For an asyncio application, asyncio.create_subprocess_exec() provides non-blocking process operations. Use create_subprocess_shell() only for deliberate shell usage. Await communicate() or read asynchronously from the process streams.
Exercise
Why should the parent close producer.stdout after giving it to consumer?
Show answer
Closing the parent's copy allows the consumer to observe end-of-file when the producer finishes.