Python subprocess Hangs: Pipes, communicate and Timeout Cleanup
Fix Python subprocess hangs caused by full pipes or missing EOF. Learn run vs Popen timeout cleanup with a tested Linux child-process lab.
A captured subprocess can hang when its parent waits without draining stdout and stderr, or leaves input open while the child expects EOF. Use run for bounded jobs, communicate for coordinated pipe I/O, and an explicit stop-and-collect policy when Popen times out.
Identify what each process is waiting for
A command that works in a terminal can stall when a Python wrapper captures its output. In the terminal, a reader normally consumes the output. With stdout=PIPE or stderr=PIPE, your program becomes responsible for that consumption. Start diagnosis by recording the exact argument list, which streams are piped, whether input is still open, and the child’s current status. A spinner that stops moving is not enough evidence to distinguish slow work from blocked I/O.
Consider a child writing a large diagnostic message to stderr. The parent calls wait without reading stderr. Once that pipe fills, the child cannot finish its write and exit; the parent is waiting for the exit that the blocked write prevents. Reading stdout to EOF first can create the same cycle when the child fills stderr before closing stdout. The solution needs to account for both streams rather than hoping one stays small.
A different stall occurs when the child expects input until EOF. Sending some bytes and flushing does not tell the child that input is complete. If the parent then waits for a result while leaving stdin open, the child may still be waiting for the rest of its request. Write down the protocol: fixed byte count, delimiter, interactive exchange or EOF. Select the subprocess interface only after that contract is clear.
| Observed wait | Possible cause | Useful next check |
|---|---|---|
| wait with captured streams | Child blocked writing to a full pipe | Drain both streams or redirect them |
| stdout read waits forever | Other stream blocked or a writer still open | Inspect stderr handling and inherited handles |
| Child awaits input | No request delimiter or stdin EOF | Check the documented input protocol |
| No output, child still running | Buffering, slow work or an external wait | Separate progress visibility from completion |
Use run for a finite command with bounded output
For a short operation whose output size you can reasonably bound, run is the clearest starting point. The example uses an argument list and the current Python executable rather than assuming that a different python on PATH points at the same installation. Its isolated child reverses a six-byte input and emits a separate diagnostic message. No shell is involved, and the output is kept as bytes until the caller deliberately decodes it.
The three decisions are independent: timeout limits the subprocess interaction, check turns an unsuccessful exit into CalledProcessError, and capture_output requests both streams. A command can finish before its deadline and still fail with a nonzero status. Conversely, a timeout does not establish that the command was defective: an unavailable dependency or an unrealistic service deadline can produce the same symptom.
Treat captured bytes as data with a defined encoding. Specify encoding when text output is part of the command’s contract; otherwise retain bytes and decode at the boundary where you know what they mean. Do not silently replace decoding errors when the content is evidence of a failed job. Also avoid logging an entire command line or captured stream if it can contain access tokens or private records.
import subprocess
import sys
result = subprocess.run(
[sys.executable, '-I', '-c',
'import sys; data=sys.stdin.buffer.read(); '
'sys.stdout.buffer.write(data[::-1]); '
"sys.stderr.buffer.write(b'diagnostic')"],
input=b'abcdef', capture_output=True, timeout=5, check=True)
assert result.stdout == b'fedcba'
assert result.stderr == b'diagnostic'Source: Python subprocess — run, Popen and timeout behavior ↗
Separate a timeout from stopping and reaping the child
When you need Popen, communicate coordinates input and output and waits for completion. Its timeout has different cleanup behavior from run: a communicate timeout leaves the child running. The caller must decide how to stop it and collect its exit. For a direct child you own, the documented pattern is to kill that child and call communicate again. Retrying communication after a timeout preserves previously collected output; do not concatenate the exception’s partial output with the final result as though they were disjoint chunks.
Choose the shutdown policy deliberately. A cooperative tool may need a terminate request and a grace interval before forced termination. On POSIX, terminate and kill use different signals; Windows behavior differs. A child can ignore a cooperative signal, so the grace period needs a defined end. Always collect the final status. Merely dropping the Python object is not a resource-management strategy.
This direct-child pattern is not a complete process-tree supervisor. A child can start descendants that keep inherited output handles open, causing output collection to continue waiting even after the original child exits. If your workload spawns a tree, use an explicit platform-appropriate containment and shutdown policy. POSIX sessions/process groups and Windows job management require separate design and testing; this article does not provide a universal cross-platform tree-kill helper.
Budget cleanup as part of the operation. A timeout value is not a precise wall-clock guarantee for process creation plus all shutdown work. If a service must return promptly, decide where the supervisor lives, what happens to partial output, and which component continues cleanup after the request ends. Returning an HTTP error while abandoning a running conversion job can amplify the next incident.
Source: Python subprocess — run, Popen and timeout behavior ↗
For large output, change where the bytes go
communicate avoids the common pipe waiting cycle by consuming streams, but it collects captured output in memory. It is suitable for bounded output, not an unlimited log feed. Before capturing a compiler, data export or media tool, estimate the largest credible output and decide whether the caller actually needs every byte. “Usually a few lines” is a poor bound when failure mode diagnostics can be enormous.
One alternative is redirecting stdout and stderr to files that you own for the job, then examining a bounded portion after completion. That moves pressure from RAM to disk, so apply disk quotas, retention and access controls appropriate to the content. Merging stderr into stdout reduces two streams to one but loses stream identity. It also does not turn an unlimited stream into a bounded result.
For live streaming, arrange concurrent consumption of both streams and define backpressure. A slow log destination can become the new blocking reader. Bound queues and stored history; decide whether to pause the producer, spill to disk or discard explicitly marked diagnostics when limits are reached. Do not write a sequential stdout-then-stderr loop and label it concurrent merely because both reads appear in the same function.
Buffering is a separate concern. A child may buffer output when connected to a pipe, so the absence of a recent line need not mean a deadlock. For a Python child, explicit flushes or an appropriate unbuffered mode can make progress visible. Increasing a pipe’s capacity or changing the parent’s buffering is not a substitute for consuming all required output and completing the input protocol.
A Linux lab with bounded output and real child processes
The complete fixture below needs Linux and Python 3. It queries the actual stderr pipe capacity with F_GETPIPE_SZ and asks its first child to write slightly more than that capacity. The child first sends a readiness marker, then waits for the parent’s instruction. This handshake reduces the chance of confusing interpreter startup with the deliberately undrained pipe. The brief wait timeout is followed by communicate so the test never intentionally leaves a blocked child behind.
The remaining cases verify an EOF-delimited input, separate stdout and stderr, a communicate timeout followed by direct-child kill and collection, and a nonzero exit with its diagnostic bytes. Every launched command is a fixed Python snippet, not a shell command or an external download. Run the fixture under an outer development-runner deadline too: its readiness reads assume these known child snippets successfully start.
This fixture passed 11 checks across four real direct children on Linux with Python 3.12.14. The queried pipe capacity in that run was 65,536 bytes; the code derives the write size instead of assuming that capacity on your machine. The timeout observation alone would not prove a deadlock in an arbitrary application, but the controlled write volume, undrained stream and successful drain establish the intended reproduction here.
The lab does not exercise descendant cleanup, Windows, interactive terminal programs, async cancellation, adversarial unlimited output or process-creation failures. Its cleanup calls assume these direct children have no descendants retaining the pipe handles. Use a disposable development environment, and keep any production wrapper’s stronger requirements separate from this small correctness experiment.
import fcntl
import subprocess as sp
import sys
def command(code):
return [sys.executable, '-I', '-c', code]
checks = 0
# A child announces readiness, then waits for instructions. This avoids
# attributing startup delays to pipe pressure.
with sp.Popen(command("import sys; print('ready',flush=True); "
"n=int(sys.stdin.readline()); "
"sys.stderr.buffer.write(b'E'*n); "
"sys.stderr.flush(); print('done',flush=True)"),
stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE) as child:
try:
assert child.stdout.readline() == b'ready\n'
capacity = fcntl.fcntl(child.stderr.fileno(), fcntl.F_GETPIPE_SZ)
n = capacity + 4096
child.stdin.write(f'{n}\n'.encode())
child.stdin.flush()
try:
child.wait(timeout=0.3)
except sp.TimeoutExpired:
checks += 1
else:
raise AssertionError('unexpected completion with undrained pipe')
out, err = child.communicate(timeout=5)
assert (out, err, child.returncode) == (b'done\n', b'E'*n, 0)
checks += 3
finally:
if child.poll() is None:
child.kill()
child.communicate()
# communicate handles both output pipes and closes input after sending it.
r = sp.run(command("import sys; data=sys.stdin.buffer.read(); "
"sys.stdout.buffer.write(data[::-1]); "
"sys.stderr.buffer.write(b'diagnostic')"),
input=b'abcdef', capture_output=True, timeout=5, check=True)
assert (r.stdout, r.stderr, r.returncode) == (b'fedcba', b'diagnostic', 0)
checks += 3
# A communicate timeout leaves this direct child alive until we stop it.
with sp.Popen(command("import sys,time; print('ready',flush=True); "
"time.sleep(30)"), stdout=sp.PIPE, stderr=sp.PIPE) as child:
try:
assert child.stdout.readline() == b'ready\n'
try:
child.communicate(timeout=0.1)
except sp.TimeoutExpired:
assert child.poll() is None
checks += 1
else:
raise AssertionError('expected timeout')
child.kill()
out, err = child.communicate(timeout=5)
assert child.returncode is not None
assert out == b'' and err == b'' # readiness was read separately
checks += 2
finally:
if child.poll() is None:
child.kill()
child.communicate()
try:
sp.run(command("import sys; sys.stderr.write('bad input'); sys.exit(7)"),
capture_output=True, timeout=5, check=True)
except sp.CalledProcessError as exc:
assert exc.returncode == 7 and exc.stderr == b'bad input'
checks += 1
else:
raise AssertionError('expected nonzero-exit exception')
print(f'{checks} checks passed; four real direct children; pipe capacity {capacity}')Verify the failure path as carefully as the successful command
Before releasing a wrapper, test a successful command, a fast nonzero exit, a slow child, output on both streams, input completion and cleanup after interruption. Record the child’s status and which stream policy applied. Keep the original failure classification when shutdown itself encounters a problem; a cleanup exception should not silently turn a timeout into an unrelated success report.
If the wrapper runs inside asyncio, use its subprocess APIs and keep the same lifetime questions visible. Awaiting a coroutine does not automatically drain every stream or terminate its external process on cancellation. asyncio’s Process methods have different timeout interfaces from Popen, so copying synchronous timeout arguments into async code is not a valid migration. Test the cancellation path independently before relying on it.
The practical repair follows the waiting relationship: complete the input contract, consume or redirect all required output, and own the child until shutdown and collection finish. Choose run for straightforward bounded work, use Popen when its extra control is needed, and give large output and process trees an explicit design. That makes a stalled wrapper diagnosable instead of merely giving it a longer timeout.
Source: Python asyncio subprocess — Process lifetime and I/O ↗
Your next steps
- Drain both captured streams or redirect them to an appropriate destination.
- Popen.communicate timeout does not itself stop the child.
- Output capture consumes memory; streaming and process trees need explicit policies.
- Test timeout and nonzero-exit paths with real child processes.
Sources & official resources
Linked resources checked on 2026-10-29. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →