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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import json
import subprocess
import sys

result = subprocess.run(
    [sys.executable, "-c",
     "import json, sys; print(json.dumps(sys.argv[1:]))",
     "level 1 & bonus.json", ""],
    shell=False,
    check=True,
    capture_output=True,
    timeout=10,
)
print(json.loads(result.stdout.decode("utf-8")))
# ['level 1 & bonus.json', '']

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import subprocess


def run_tool(argv, *, cwd=None, timeout=30):
    """Run a trusted executable and return its UTF-8 stdout on success."""
    if not isinstance(argv, (list, tuple)) or not argv:
        raise TypeError("argv must be a nonempty list or tuple")
    if any(not isinstance(arg, str) for arg in argv):
        raise TypeError("Every argument must be a string")
    if not argv[0]:
        raise ValueError("The executable path must not be empty")
    if isinstance(timeout, bool) or not isinstance(timeout, (int, float)):
        raise TypeError("timeout must be a number")
    if not 0 < timeout < float("inf"):
        raise ValueError("timeout must be positive and finite")

    result = subprocess.run(
        argv,
        cwd=cwd,
        stdin=subprocess.DEVNULL,
        shell=False,
        check=False,
        capture_output=True,
        timeout=timeout,
    )
    # Decode in the caller, after both binary streams have been collected.
    result.stdout = result.stdout.decode("utf-8").replace("\r\n", "\n").replace("\r", "\n")
    result.stderr = result.stderr.decode("utf-8").replace("\r\n", "\n").replace("\r", "\n")
    result.check_returncode()
    return result.stdout

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import subprocess
import sys

from tool_runner import run_tool

try:
    output = run_tool([
        sys.executable, "-c",
        "import sys; print('invalid asset', file=sys.stderr); sys.exit(7)",
    ])
except subprocess.CalledProcessError as exc:
    print(f"Tool failed with exit code {exc.returncode}")
    print(exc.stderr.strip())
except subprocess.TimeoutExpired:
    raise SystemExit("Tool exceeded its time budget")
except OSError as exc:
    raise SystemExit(f"Could not start tool: {exc}")
else:
    print(output, end="")
# Tool failed with exit code 7
# invalid asset

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import json
import subprocess
import sys
import unittest

from tool_runner import run_tool


class ToolRunnerTests(unittest.TestCase):
    def test_literal_arguments(self):
        values = ["level 1 & bonus.json", "", 'a"b', "*.png", "a;b"]
        output = run_tool([
            sys.executable, "-c",
            "import json, sys; print(json.dumps(sys.argv[1:]))",
            *values,
        ])
        self.assertEqual(json.loads(output), values)

    def test_nonzero_exit_retains_both_streams(self):
        with self.assertRaises(subprocess.CalledProcessError) as caught:
            run_tool([
                sys.executable, "-c",
                "import sys; print('partial'); "
                "print('bad input', file=sys.stderr); sys.exit(7)",
            ])
        error = caught.exception
        self.assertEqual(error.returncode, 7)
        self.assertEqual(error.stdout, "partial\n")
        self.assertEqual(error.stderr, "bad input\n")

    def test_stalled_child_times_out(self):
        with self.assertRaises(subprocess.TimeoutExpired):
            run_tool([
                sys.executable, "-c", "import time; time.sleep(30)",
            ], timeout=0.5)

    def test_invalid_utf8_in_either_stream(self):
        for stream in ("stdout", "stderr"):
            with self.assertRaises(UnicodeDecodeError):
                run_tool([
                    sys.executable, "-c",
                    f"import sys; sys.{stream}.buffer.write(bytes([255]))",
                ])

    def test_invalid_contract(self):
        command = [sys.executable, "-c", "pass"]
        for value in (0, -1, float("inf"), float("nan")):
            with self.assertRaises(ValueError):
                run_tool(command, timeout=value)
        for value in (None, True, "5"):
            with self.assertRaises(TypeError):
                run_tool(command, timeout=value)
        for argv in ([], "python --version", [sys.executable, 1]):
            with self.assertRaises(TypeError):
                run_tool(argv)
        with self.assertRaises(ValueError):
            run_tool([""])


if __name__ == "__main__":
    unittest.main()

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.