← Blog
A lavender ticket dispenser with an orange side knob and a blank ivory paper strip.
Published on
2026-11-19

Python subprocess: commands, output, and timeouts

Python subprocess runs another program from your Python application. It is useful when a worker needs to call a command-line tool, inspect its result, and decide whether the job succeeded. Start with subprocess.run() when the caller can wait for one command to finish. Pass an argument list, choose how to handle output, and set both an exit-code policy and a timeout.

This guide builds a small runner around an owned Python command. The example makes no network requests and operates inside a temporary directory. It demonstrates successful output, an intentional failure, a sleeping process, and file output without depending on a tool installed elsewhere on your computer.

Choose run() for a command you can wait for

A subprocess is a separate operating-system process. Use it when the operation already exists as an executable or script. For parallel Python functions, see Python multiprocessing. For coordinating asynchronous work, see Python asyncio. Those decisions concern how your application organizes work; this example concerns the boundary between a caller and an external command.

The Python subprocess reference recommends run() for the cases it can handle. It returns a CompletedProcess when it completes normally. Choose Popen when you need direct control over a running process. Its pipe management and cleanup become your responsibility; communicate(timeout=...) does not kill a child on timeout by itself.

Our wrapper uses check=True so a nonzero exit becomes an exception, captures small outputs as UTF-8 text, and sends larger output directly to a file. These are separate choices. A command can finish within its timeout and still return an error.

Create a command with predictable behavior

Save the following as child_tool.py. It accepts a mode and a label. The normal mode emits JSON to standard output and a synthetic diagnostic to standard error. The other modes return exit code 7, sleep for 30 seconds, or write exactly 1 MiB across the two output streams.

The PID file lets the accompanying checks verify that the process has exited. The environment check uses a synthetic variable name; no real credential is needed. This is a teaching fixture, not a general command-execution endpoint.

"""An owned command-line fixture. It performs no external operation."""
import argparse
import json
import os
from pathlib import Path
import sys
import time


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("mode", choices=["echo", "fail", "sleep", "bulk"])
    parser.add_argument("label")
    args = parser.parse_args()
    Path("child.pid").write_text(str(os.getpid()), encoding="ascii")
    if args.mode == "bulk":
        for _ in range(64):
            sys.stdout.buffer.write(b"O" * 8192)
            sys.stderr.buffer.write(b"E" * 8192)
        return 0
    report = {
        "label": args.label,
        "cwd": str(Path.cwd()),
        "job": os.environ.get("DEMO_JOB"),
        "parent_secret_visible": "SUBPROCESS_DEMO_SECRET" in os.environ,
        "stdin": sys.stdin.read(),
        "pid": os.getpid(),
    }
    print(json.dumps(report, ensure_ascii=False), flush=True)
    print("synthetic diagnostic", file=sys.stderr, flush=True)
    if args.mode == "sleep":
        time.sleep(30)
    return 7 if args.mode == "fail" else 0


if __name__ == "__main__":
    raise SystemExit(main())

Pass explicit arguments, a directory, and an environment

Save this second file as runner.py in the same directory. It uses the current Python interpreter and the absolute path to the child script. The caller supplies a working directory, so the child’s relative files have a deliberate destination.

"""Run only the owned child fixture, with a small explicit environment."""
import math
import os
from pathlib import Path
import subprocess
import sys

PYTHON = str(Path(sys.executable).resolve())
CHILD = str(Path(__file__).with_name("child_tool.py").resolve())


def options(mode, label, cwd, timeout):
    if mode not in {"echo", "fail", "sleep", "bulk"}:
        raise ValueError("Unsupported fixture mode")
    if not isinstance(label, str) or len(label) > 200 or "\0" in label:
        raise ValueError("Label must be at most 200 characters without NUL")
    if not isinstance(timeout, (int, float)) or not math.isfinite(timeout) or timeout <= 0:
        raise ValueError("Timeout must be a positive finite number")
    env = {key: os.environ[key] for key in ("SystemRoot", "WINDIR", "TEMP", "TMP", "TMPDIR")
           if key in os.environ}
    env.update(DEMO_JOB="catalog-check", PYTHONIOENCODING="utf-8")
    return {
        "args": [PYTHON, CHILD, mode, "--", label],
        "cwd": str(Path(cwd).resolve()),
        "env": env,
        "shell": False,
        "stdin": subprocess.DEVNULL,
        "check": True,
        "timeout": timeout,
        "creationflags": getattr(subprocess, "CREATE_NO_WINDOW", 0),
    }


def run_small(mode, label, cwd, timeout=2):
    if mode == "bulk":
        raise ValueError("Use file output for the bulk fixture")
    return subprocess.run(**options(mode, label, cwd, timeout),
                          capture_output=True, text=True, encoding="utf-8")


def run_to_file(mode, label, cwd, log_path, timeout=2):
    config = options(mode, label, cwd, timeout)
    with Path(log_path).open("xb") as log:
        return subprocess.run(**config, stdout=log, stderr=subprocess.STDOUT)

Each argument is a separate list entry. In the checks, spaces, Unicode, quotes, and shell-like characters arrived as literal label text. The -- delimiter is understood by this child’s argparse parser and allows a label such as --help. Check the option syntax of any replacement tool before using the same pattern.

shell=False does not authorize the operation or validate the target program’s options. Keep the executable and script under your control, constrain allowed operations, and validate paths according to the job. Windows .bat and .cmd files have an additional shell-parsing caveat described in Python’s security considerations. This example invokes the Python executable directly.

The explicit environment gives the child a small set of operating-system variables plus two values this example needs. Our test confirmed that an unlisted synthetic parent secret was absent. A replacement program may require other variables or a search path. Add those deliberately; copying the entire parent environment can expose values the child does not need.

Standard input is DEVNULL, so the child reads an empty input stream instead of waiting for a terminal. This suits a noninteractive worker. A tool that needs input requires a different, explicit input policy.

Handle success, nonzero exits, and timeouts separately

Save demo.py beside the other two files and run it with your Python interpreter. No third-party packages are required. The temporary directory is removed when the demonstration finishes.

import json
from pathlib import Path
import subprocess
from tempfile import TemporaryDirectory
from runner import run_small, run_to_file


def main():
    with TemporaryDirectory(prefix="subprocess-demo-") as directory:
        root = Path(directory)
        result = run_small("echo", "caf\u00e9 & report", root)
        print("Success:", json.loads(result.stdout)["label"])
        try:
            run_small("fail", "example", root)
        except subprocess.CalledProcessError as error:
            print("Child exit code:", error.returncode)
        try:
            run_small("sleep", "example", root, timeout=0.5)
        except subprocess.TimeoutExpired:
            print("Child exceeded its wait limit")
        log = root / "job.log"
        run_to_file("bulk", "example", root, log)
        print("Combined output bytes:", log.stat().st_size)


if __name__ == "__main__":
    main()

The successful call prints Success: café & report. The intentional failure reports exit code 7, the sleeping call reports that it exceeded its wait limit, and the file-output call reports 1048576 bytes.

Three failure categories need different responses. A missing executable or invalid working directory is a launch error, usually represented by an OSError subclass. A command that starts and returns a nonzero code raises CalledProcessError with this wrapper. A child that exceeds the configured wait raises TimeoutExpired. The exact launch-error subclass can depend on the operating system.

Without check=True, a nonzero return code must be inspected explicitly; our separate check returned code 7 without raising. With captured output, the failing command’s output remains available on the exception. Decide what is appropriate to retain before logging it. Arguments and command output may contain private data, so the demonstration prints only the exit code. The Python logging guide covers structured operational records.

Give runtime and output their own limits

For run(), Python documents that a timeout kills and waits for the direct child before raising. Process creation can delay when the timeout is reported. This is not a guaranteed end-to-end deadline or a promise to stop every descendant process. Consult the run() timeout behavior when defining the job’s deadline.

Our sleeping fixture had exited before the timeout handler ran. It creates no descendants, so that result says nothing about terminating a whole process tree. If a real tool launches helpers, test your supervisor’s cleanup on the deployment operating system. Stopping a process also does not undo files it wrote or requests it sent.

run_small() is for this fixture’s small, predictable response. It has no general output-size ceiling. Do not use memory capture for an uncontrolled stream and assume that a timeout makes the memory use safe.

run_to_file() sends standard output and standard error into one file. The exclusive xb mode refuses to overwrite an existing file, and the context manager closes the handle on success, failure, or timeout. Partial output remains for the caller to inspect. Combining streams does not guarantee the order in which the application originally produced messages, because buffering still matters.

File output shifts the storage requirement to disk. It does not impose a disk quota or retention policy. Set those separately for a production worker, along with limits on simultaneous jobs. Keep the job directory controlled by the application and account for incomplete outputs when a task stops.

What the example verified

The exact example files passed 44 functional checks with Python 3.12.14 on Windows. The checks used real child processes and disposable local files, including operating-system checks that the timed-out children had exited.

CaseObserved result
Successful commandCode 0; separate stdout and stderr; explicit directory and environment
Labels with spaces, Unicode, quotes and shell-like syntaxLiteral values preserved; no redirected marker file created
Nonzero exit and launch failuresCode 7 raises with check=True; missing executable and directory produce launch errors
Sleeping commandTimeout raised; direct child confirmed exited; earlier output retained
File outputExactly 1 MiB written; no captured buffers; existing log not overwritten
Failure and timeout with file outputPartial output retained and file handles closed
Cleanup and complete demonstrationTemporary directory removed; standalone demo finishes with expected results

These results establish the demonstrated behavior on that runtime. They are not a Linux process-group test, a cloud deployment test, or a throughput benchmark. The file-output test confirms redirection and cleanup, not a hard output quota.

Run the command inside an application worker

Before connecting this pattern to a service, define who can request each operation, which files it can read, and what counts as a completed job. Keep the executable location stable, apply operating-system permissions, and limit concurrent children. A synchronous run() call occupies its caller until the command finishes; a long operation needs an appropriate worker rather than an unbounded wait inside an application request.

Retries require their own decision. After a timeout, a tool may already have produced part of its result. Use job identifiers, inspect partial artifacts, and decide whether the operation can be repeated. The data pipeline orchestration guide covers dependencies and retries beyond a single command.

If the application needs a VM where you install and operate its tools, CPU instances from Compute with Hivenet are one hosting option. You manage the command, permissions, updates, resource limits, monitoring, and recovery. Compare that responsibility with other deployment models in the API hosting guide before choosing where the worker should run.

Your next workload belongs on Hivenet.

Pick one AI, compute, or storage workload and see the difference for yourself. Spin it up in minutes, or let our team map your fastest path to production.