Python subprocess hangs: choose an output budget
Draining both pipes solves one deadlock. Output retention and child ownership still need explicit limits.
Quick answer
Python subprocess hangs with piped output often occur because the parent waits for exit while the child waits for pipe space. Drain both streams with communicate for predictably bounded output, or send large output directly to managed files. Define timeout cleanup and descendant ownership separately; changing the wait call alone does not bound resource use.
On this page
Python subprocess hangs with piped output often occur because the parent waits for exit while the child waits for pipe space. Drain both streams with communicate for predictably bounded output, or send large output directly to managed files. Define timeout cleanup and descendant ownership separately; changing the wait call alone does not bound resource use. [1][2]
Why does wait hang when the command works alone?#
Redirecting output changes the communication path. A child that writes successfully to a terminal may block when its output goes into a pipe that nobody reads. If the parent calls wait() while the child is blocked writing, each process waits for progress the other cannot make. Python documents this failure for piped standard output and standard error. [1]
The same mistake can hide behind apparently careful code. Reading standard output to completion and then reading standard error can block when the child fills standard error before closing standard output. A reader must handle the streams together, or the design must avoid those pipes.
Do not begin by increasing the timeout. First establish what the child is waiting for. It may need an input record, a newline, an EOF on standard input, an external service, or a reader for its output. Those causes can look similar in a job dashboard but require different repairs.
Scenario: a fictional report worker launches a converter that emits a small summary on standard output and extensive diagnostics on standard error. The worker used to inherit the terminal. After a wrapper redirects both streams into pipes for logging, some reports stop completing. The converter, input and output volume here are controlled demonstration data, not a customer incident.
Record where that exact child sends its input, output and diagnostics. Record the argument list, working directory, input ownership, stream destinations and return-code policy. Avoid recording credentials embedded in command arguments. A successful manual invocation with different stream destinations is useful comparison evidence, not a reproduction of the wrapper’s behavior.
Reproduce the blocked-pipe cycle#
Use a disposable child that writes a fixed amount of diagnostic data before printing its summary. A short wait timeout makes the failure observable without leaving a deliberately blocked process running indefinitely. The cleanup drains the streams after killing the direct child, as the subprocess documentation recommends for that lifecycle. [1]
import subprocess
import sys
child = (
"import os; "
"chunk = b'x' * 65536; "
"[os.write(2, chunk) for _ in range(256)]; "
"print('finished')"
)
proc = subprocess.Popen(
[sys.executable, '-c', child],
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
try:
proc.wait(timeout=1)
print('child completed before timeout')
except subprocess.TimeoutExpired:
print('wait did not drain the diagnostic pipe')
proc.kill()
finally:
out, err = proc.communicate()Scenario: the child’s fixed output is deliberately much larger than ordinary pipe buffers. The test should observe the blocked wait and then remove its own child. It should not assert a universal buffer capacity or exact amount written before blocking. Those details vary by platform and execution environment.
Changing the parent to communicate() while keeping the same fixed child tests the proposed repair. The subprocess module was designed to coordinate input and both output streams; its original design rationale calls out the difficulty of implementing this communication correctly by hand. [3]
This negative control has a narrow purpose. It shows that waiting without draining can prevent this particular child from exiting. It does not establish that every hung converter has the same cause, and it does not measure converter throughput. Retain the child code with the result so another engineer can see exactly which behavior was exercised.
When is captured output small enough?#
Captured output is appropriate when the producer’s output is predictably bounded and the wrapper can afford to retain it. communicate() resolves the pipe coordination problem by reading output, but the captured data is held in memory. The async subprocess API has the same memory warning; switching to an event loop does not create an output-retention limit. [1][2]
For the fictional converter, a summary-only mode may have a documented finite result while verbose diagnostics do not. Make that distinction part of the invocation contract. The timeout limits how long a healthy wait is allowed to continue; it is not a byte limit. Checking len(result.stdout) after completion can reject a large result, but the allocation has already happened.
import subprocess
def capture_summary(argv, timeout):
# Precondition: this trusted command has a bounded output contract.
result = subprocess.run(
argv,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=timeout,
check=False,
)
if result.returncode != 0:
raise RuntimeError(
f'converter failed with status {result.returncode}'
)
return result.stdout, result.stderrThe wrapper preserves bytes. Decode a known text format at the boundary where its encoding is established. Python text streams produce strings and may perform decoding and newline translation, while binary streams preserve bytes. This distinction matters for generated artifacts and for diagnostics whose encoding is uncertain. [4]
Save a diagnostic artifact or a bounded tail; do not copy an entire error stream into the exception. Save an artifact reference or a deliberately bounded tail under an agreed retention policy. A failure handler that joins an entire captured stream into a log message can repeat the original memory and storage problem elsewhere.
For untrusted or uncontrolled producers, choose an output design that enforces the resource budget during execution. A library call that collects everything and checks afterward does not provide that protection. Depending on the workload, use a streaming reader with a tested stop policy, a quota-controlled filesystem, or a supervisor that owns both storage and process limits.
How should a large export write output?#
Send the export to a file rather than retaining it in the parent’s captured output. Keep diagnostics in a separate file if the artifact must remain parseable. The following skeleton controls the direct child and leaves partially written files available for diagnosis; its caller must provide a task-owned directory and retention policy.
from pathlib import Path
import subprocess
def export_to_files(argv, directory, timeout):
directory = Path(directory) # Existing, private, task-owned directory.
output = directory / 'report.part'
errors = directory / 'converter.stderr'
with output.open('xb') as out, errors.open('xb') as err:
subprocess.run(
argv,
stdin=subprocess.DEVNULL,
stdout=out,
stderr=err,
timeout=timeout,
check=True,
)
return output, errorsThe exclusive file mode refuses to reuse an existing pathname. Give each invocation its own directory so a retry cannot accidentally treat another attempt’s partial output as success. Do not rename the partial artifact to a final name merely because the child exited successfully. Validate the report’s format, expected scope and completion marker first.
File-backed output moves the retention cost to storage. It does not eliminate the cost. A noisy child can fill the filesystem, and a timeout cannot guarantee an acceptable maximum file size. Apply a storage quota or a separate enforced size policy when that is a requirement. Include the resulting write failure in the child’s tested failure contract.
Using stderr=STDOUT can simplify a human-readable command log, but it combines diagnostics with the artifact stream. For a JSON, CSV or binary report, that can corrupt the deliverable. Choose stream merging because the output format permits it, rather than because it removes a second file handle.
| Output contract | Suitable destination | Separate obligation |
|---|---|---|
| Small trusted summary | Captured pipes with coordinated draining | Producer bound and parent memory allowance |
| Large report artifact | Task-owned file | Storage budget and content validation |
| Continuous diagnostics | Managed streaming sink | Backpressure, rotation and sink failure behavior |
| Discardable noise | DEVNULL | Confirm that diagnostic loss is acceptable |
What happens to descendants and cleanup?#
A direct-child timeout is not a general process-tree supervisor. If the launched command creates descendants, those descendants can outlive it or retain inherited output handles. A parent may be gone while an output pipe still has a writer. Treat the process tree and the stream lifetime as related but separate objects.
Python’s low-level Popen.communicate(timeout=...) raises on timeout without automatically killing the child; the documented recovery is to kill it and finish communication. The higher-level run(timeout=...) owns direct-child killing and waiting. Neither description should be expanded into a promise that arbitrary descendants, remote jobs or side effects have stopped. [1]
On Unix, a dedicated session or process group can be part of a supervised design. The os.killpg API sends a signal to a process group. It is Unix-specific and only controls processes that remain in that group; a child that deliberately changes its process relationships needs a stronger containment policy. Do not paste a group-kill recipe into a cross-platform wrapper and call it portable. [6]
Also avoid replacing subprocess timeouts with ad hoc signal-handler installation inside worker threads. Python restricts installing new signal handlers to the main thread of the main interpreter. A wrapper that works in a command-line experiment may fail when called by a threaded job runner. Prefer a lifecycle mechanism supported by the actual runner and platform. [5]
Name the objects cleanup must leave finished: the child, its handles and any partial artifacts. For a simple child it can mean return code collected, stream handles closed and partial files recorded. For a converter tree it may additionally require the supervisor to confirm no owned descendants remain. For a tool that started remote work, local cleanup may leave a reconciliation task rather than a completed cancellation.
Which tests establish that the wrapper is finished?#
Attach an artifact state to each outcome: incomplete, rejected or accepted. A timeout can leave a useful partial file, but the next stage must not infer completeness from its existence. A nonzero exit can leave a plausible report prefix too. Promote only after the command and content checks both pass, then record which invocation produced the accepted artifact.
Retain the cleanup result separately from the command result. If the converter fails and a storage or supervision problem also prevents cleanup, preserve both observations. Replacing the original error with a generic timeout hides the evidence the next operator needs. For a small wrapper, returning a structured outcome to the job runner is often clearer than constructing a large exception from captured output.
Exercise success, noisy failure and timeout under the wrapper’s real stream configuration. The useful assertion is that each outcome has a known artifact state and no unowned local work. A test that merely receives a timeout exception can pass while the child or its descendants continue running.
For the sample report worker, retain these cases with their observed results:
- A child fills standard error before writing standard output.
- Both streams contain finite output and the successful capture matches it.
- A nonzero exit leaves a useful failure record without promoting an artifact.
- A timeout cleans up the direct child and retains partial files as incomplete.
- A descendant keeps an inherited pipe open after its parent exits.
- A rerun uses a fresh directory and cannot accept an earlier partial report.
Run the descendant case only with a test-owned process group or equivalent supervisor, and tear it down explicitly. It is an adverse test of the wrapper boundary, not an invitation to leave background processes behind.
The same ownership issue appears when an asyncio timeout leaves a thread running. In both situations, the waiting operation can end before the owned work ends. For an HTTP export stage, the response-body timeout guide shows why completion must cover the body as well as the initial response.
What else should you verify?#
- Does bufsize fix a parent that never reads?
- No. Adjusting buffering does not make the parent consume both output streams. Establish who drains each stream, then choose bounded capture or an appropriate output destination. Test with a child that produces substantial diagnostics. [1]
- Is communicate suitable for unlimited output?
- No. Captured output is retained in memory. Use a managed destination or a tested streaming policy when the producer can emit large or unbounded output. An output-length check after collection is too late to prevent the allocation. [1][2]
- Does run timeout stop every descendant?
- Do not treat it as a process-tree guarantee. It handles the direct child’s timeout lifecycle. Descendants, inherited handles and remote work need an ownership and containment design appropriate to the platform and command being launched. [1][6]
- Can a zero exit code promote the report immediately?
- Only when the application’s output contract says that is sufficient. A report worker should also verify artifact completeness, expected scope and format. Keep partial outputs distinguishable from approved deliverables and give retries their own task-owned paths.