Run Python Subprocesses with Argument Lists, Checks, and Timeouts
A game asset pipeline calls a converter with a filename such as level 1 & bonus.json. The filename should arrive as one argument. If conversion fails or stalls, the pipeline should stop before publishing its output.
Build a small command runner around subprocess.run. The examples below use Python 3.7 or later on a desktop or build server. They launch the current Python interpreter as a stand-in for a converter, so you can reproduce every case without installing another program.
Pass Each Argument Separately
Start with an argument round trip:
| |
Each list element represents one argument; do not add shell quotes around a filename or split a constructed command string on spaces. Here, the empty argument is intentional and the ampersand is filename data.
Use a configured executable path for a real converter.
sys.executable
identifies the running Python interpreter, including a virtual environment’s interpreter. This example assumes a normal installation where that value is available.
Define a Small Command Contract
Save this as tool_runner.py:
| |
The
run reference
defines checked exit codes, captured streams, and timeout handling. This helper requires a positive, finite timeout and closes interactive input with DEVNULL.
Choose UTF-8 only when it matches the tool’s output contract. A legacy converter may need another encoding. Capture bytes and decode both streams in the calling thread so invalid UTF-8 reliably raises UnicodeDecodeError, including on Windows. The helper normalizes line endings to \n, then checks the exit status. Decoding failure therefore takes precedence over a nonzero exit code.
Set cwd when the converter expects a project directory. Keep the executable path absolute; resolve input and output paths deliberately relative to the chosen working directory. Avoid changing the parent process’s directory just to run one tool.
Keep Failures Visible to the Caller
Run this beside tool_runner.py:
| |
This demonstration reports the expected rejection. In a publishing script, re-raise the exception or exit nonzero after reporting it. Do not let an error handler return normally and continue to upload an old artifact.
CalledProcessError retains the decoded text from both streams after a nonzero exit. A missing executable instead raises an operating-system error. A timeout is a third failure category; inspect it separately when deciding whether a retry makes sense. TimeoutExpired can carry partial binary output because the helper has not reached its decoding step. An uncaught UnicodeDecodeError also stops the caller.
Keep retries outside the helper. Before retrying a converter, decide what should happen to its partially written output. For this asset pipeline, a fresh temporary output path per attempt makes the final publish step easier to reason about.
Test Arguments, Exit Codes, and a Timeout
Save this as test_tool_runner.py beside the module, then run it with your Python 3 interpreter:
| |
The tests launch real child processes. The argument check covers values that commonly break hand-built command strings, while the nonzero-exit check ensures partial output cannot be mistaken for success. The timeout test expects an exception, without requiring an exact wall-clock duration.
Add a small real asset conversion to your own integration tests. Confirm its output format before promoting the result to the release directory.
Match the Runner to the Tool
Captured output stays in memory. For large logs, redirect streams to files instead. A run timeout kills and waits for the direct child; it is not a process-tree cleanup policy or an exact total wall-clock deadline. Tools that spawn workers need a separate lifecycle design.
This recipe targets executables, not Windows .bat or .cmd wrappers, which can involve a shell even with shell=False. Consult Python’s
security considerations
for that boundary.
An argument list also leaves the converter’s own option parser in control. If a filename can start with -, follow that converter’s documented end-of-options convention. Keep the executable and options under application control, and pass user-selected asset paths only in the intended operand positions.