
A Python script can launch another program and continue as though everything worked, even when that program returned an error. It can also wait longer than expected or split a filename incorrectly if the command was assembled as one shell-style string.
I would make three decisions explicit: the program and its separate arguments, what counts as failure, and how long the script should wait. Python's subprocess.run() supports all three without requiring a shell.
Use a small, controlled example
This Python 3.7-or-later example starts the current Python interpreter and asks it to print a fixed message. The child code is a constant supplied by the script, not text from a user or a downloaded file:
import subprocess
import sys
if not sys.executable:
raise RuntimeError("Python executable path is unavailable")
try:
result = subprocess.run(
[sys.executable, "-c", "print('child completed')"],
check=True,
timeout=10,
capture_output=True,
text=True,
)
except subprocess.TimeoutExpired:
raise SystemExit("The child exceeded the wait limit")
except subprocess.CalledProcessError as error:
raise SystemExit(f"The child failed: exit {error.returncode}")
except OSError as error:
raise SystemExit(f"The child could not start: {error}")
else:
print(result.stdout, end="")
The expected successful message is "child completed". That is the behavior of the supplied example, not evidence that your own command has succeeded. Replace the example only after deciding which trusted program should run and what arguments it supports.
Keep arguments separate from shell syntax
The first list element identifies the executable. Each later element is one argument. Python generally recommends this sequence form because it handles argument quoting, including filenames with spaces. You do not add shell quote characters around an individual filename inside the list.
The default is shell=False. Shell features such as pipes, wildcards and environment-variable expansion are not a reason to glue untrusted text into a command string. If a program needs input data, use its supported input interface rather than turning that data into executable code.
Separate arguments are not a sandbox. The chosen program can still interpret an argument as an option, access files or run code. In particular, never put untrusted text into the -c argument in this demonstration. Windows batch files also have special shell-parsing behavior documented by Python; do not assume this executable example covers every batch-file case.
Distinguish a failed command from a failed launch
check=True raises CalledProcessError when the child exits with a nonzero status. Without that option, inspect result.returncode yourself before treating the operation as successful. Printing whatever appeared on standard output is not an exit-status check.
A program that could not start is different. Python documents OSError for failures such as a missing executable. Keep that case separate from a program that started, ran and reported failure. Use a known executable path where possible; the documentation recommends sys.executable when launching the current Python interpreter again.
Set realistic limits on waiting and output
For run(), a timeout causes Python to kill and wait for the child before raising TimeoutExpired. However, process creation itself cannot always be interrupted immediately. A ten-second timeout is not a guarantee that your entire script returns in exactly ten seconds.
The sample captures output because the child prints one short line. Captured output is buffered in memory, so that pattern is unsuitable for an unlimited log stream or a huge export. Choose an output strategy appropriate to the real tool, and avoid exposing secrets in diagnostics.
My stopping point is an explicit success result, a distinct error path and bounded expectations for waiting and output. Those checks make a wrapper easier to trust, but they do not make an arbitrary external program safe or authorize retrying an operation that may already have changed something.
Comments
Post a Comment