Python subprocess:子进程、管道与超时清理
运行自建子进程,逐项验证参数、输出、失败、实时流、两级管道和进程回收。
学完这一章,你能够
- 运行自建子进程,逐项验证参数、输出、失败、实时流、两级管道和进程回收。
用 run 启动并取得结果
subprocess 用于创建外部进程,能分别控制输入、输出、工作目录和环境。过去常用 os.system 或 os.popen,现有程序可按需要迁到 run 或 Popen。程序调用时优先传参数列表并保持 shell=False。实验把空格、引号和 & 放在独立参数中,直接检查子进程收到的实际字符串。
run 等待子进程结束,返回 CompletedProcess。可读取 args、returncode、stdout、stderr。capture_output=True 为两条输出分别创建管道。默认捕获为 bytes,text=True 或指定 encoding 时可按文本处理。未捕获的输出字段通常为 None。
分开处理输入、状态码与启动异常
input 给 run 一次性写入 stdin。实验将三行文本交给本机过滤程序,正常结果和诊断分别出现于 stdout 与 stderr。要合流时显式设 stdout=PIPE、stderr=STDOUT,合并内容从 stdout 读取。
run 默认 check=False,即使退出码非零也返回结果。check=True 时非零退出抛 CalledProcessError,可读取异常的 returncode 与已捕获输出。找不到可执行文件通常在启动阶段抛 FileNotFoundError;子进程打开一个缺失数据文件属于另一种失败。
cwd 指定子进程工作目录,env 提供其环境。需要保留原环境时先复制,再只改想传入的项。stdout 可重定向到已经打开的文件。stdin=None 继承可用的父进程输入句柄,PIPE 让调用者写入。
管理 Popen、实时输出和双进程管道
Popen 返回进程对象。poll() 查询当前状态,运行中为 None;wait() 等待并返回退出码。有限的双向输入输出用 communicate() 一次发送输入、排空两条输出并等待,避免因只读取一条管道而相互阻塞。大量输出应设计消费策略,communicate 会把捕获结果留在内存。
实时输出要求子进程主动刷新,还要设计停止条件。本站子进程先刷新第一行并等待父进程确认,父进程收到该行时 poll() 仍为 None,回送确认后读第二行并回收。只读到空串表示流已到末尾,进程状态仍须查询。实验用超时约束等待。
把生产者 stdout 接给消费者 stdin 可实现无需 Shell 的实际管道。连好后关闭父进程持有的生产者 stdout 副本,消费末级输出,最后等待两端并分别核对退出码。实例过滤三行并得到两条命中。
持续读取日志时,文件暂时读不到新字节只表示此刻已到文件末尾。GNU tail -f 会继续跟踪新增内容。本站用自编 Python 子进程跟踪一个临时追加日志,在 Windows 上实测。父进程先读到启动记录,再分两次写入同一行 UTF-8,其中第一次在一个汉字的字节中间停下。读端等到完整换行才解码,随后继续收到下一次追加。三条日志均在子进程仍运行时收到。父进程用有时限的队列读输出,最后显式终止子进程并等待回收,随后管道读到 EOF。此例跟踪同一个文件,日志轮换时需选择按文件名跟踪或另行处理。 解压本章 ZIP 后运行 python subprocess-lab/follow_log.py,查看追加顺序、子进程状态和关闭结果。
区分 Shell、历史接口和平台差异
Shell 才解析管道、重定向和条件运算符。示例先用固定文本运行两条本机命令,再用 Windows 自带 findstr 接收一条管道数据。Shell 字符串不要拼接外部输入。不同平台提供的内建命令和程序不同,ls、grep、tail 及 echo 不能假定可直接按同一方式运行。
Windows 从 Python 3.12 起改变了 shell=True 的 Shell 查找规则。它仍会解释命令文本。Windows 的批处理文件也可能由系统交给 Shell 解析。实例传递给直接子进程的字符串与 Shell 输入分开处理。
call 返回退出码,check_call 成功时返回 0、失败抛异常,check_output 返回捕获的 stdout、失败也抛异常。新代码通常用 run 表达同样的需求。不要给不主动读取输出的 call 或 wait 留下可能写满的管道。
实测超时与进程回收
run(timeout=...) 超时会终止并等待直接子进程,然后抛 TimeoutExpired。Popen 构造器没有 timeout 选项。wait(timeout=...) 或 communicate(timeout=...) 超时本身不终止子进程,应按程序策略终止,再收尾并读取输出。
POSIX 上 terminate 发 SIGTERM,kill 发 SIGKILL。Windows 上 terminate 调用 TerminateProcess,kill 是其别名。本站让一个中间进程启动工作进程,工作进程继承同一条输出管道。终止中间进程并用 wait 确认退出后,communicate 仍会超时,因为后代仍持有管道。父进程发出协作退出信号后,工作进程继续写出一行,管道才读到 EOF。若命令会派生后代,要分别设计停止机制和管道关闭条件。解压本章 ZIP 后在 Windows 运行 python subprocess-lab/process_tree.py 可复测。
解压本站 ZIP 后运行 python python-subprocess.py。查看逐项记录中的输入、操作、预期、实际值。实测仅使用本机临时文件、固定 Shell 命令和 Python 子进程。
需要在 Windows 上按组管理自己启动的进程时,可以用 Job Object。先把中间进程加入新建的 Job,再允许它创建工作进程。用 IsProcessInJob 确认后代属于同一个 Job 后,TerminateJobObject 可强制终止组内进程。本站实测两者都以设定的 23 退出,输出管道随之关闭。组的成员资格取决于创建方式、继承和脱离设置。强制终止会中断应用清理,有机会时先使用上一段的协作退出方式。解压本章 ZIP 后在 Windows 运行 python subprocess-lab/windows_job.py 可复测。
运行接口
| 成员或参数 | 作用和条件 |
| subprocess.run(args, …) | 等待命令结束,返回 CompletedProcess;可配置捕获、超时及检查退出码。 |
| subprocess.Popen(args, …) | 启动并返回进程对象,可控制流与生命周期。 |
| subprocess.call(args, …) | 旧接口。等待并返回退出码。 |
| subprocess.check_call(args, …) | 退出码为 0 则返回 0,否则抛 CalledProcessError。 |
| subprocess.check_output(args, …) | 返回捕获的 stdout,默认 bytes,非零退出抛 CalledProcessError。 |
CompletedProcess 字段
| 成员或参数 | 作用和条件 |
| args | 启动时使用的参数对象,可为序列或字符串。 |
| returncode | 子进程退出状态,0 通常表示成功。POSIX 负数可表示因信号退出。 |
| stdout | 捕获的标准输出,bytes 或文本 str。未捕获为 None。 |
| stderr | 单独捕获的诊断流,合流时此字段为 None。 |
Popen 方法与标准流
| 成员或参数 | 作用和条件 |
| poll() | 读取当前状态。进程运行时返回 None,结束后返回退出码。 |
| wait(timeout=None) | 阻塞直到退出并返回退出码。超时抛 TimeoutExpired。 |
| communicate(input=None, timeout=None) | 送入数据并排空输出,返回 (stdout, stderr) 后完成等待。 |
| terminate() | 请求终止直接子进程。POSIX 为 SIGTERM,Windows 使用 TerminateProcess。 |
| kill() | POSIX 为 SIGKILL,Windows 与 terminate 相同。 |
| stdin | 设置 stdin=PIPE 时提供可写流,通常用 communicate 管理。 |
| stdout | 设置 stdout=PIPE 时提供可读流。 |
| stderr | 设置 stderr=PIPE 时提供独立可读流,避免只读另一条管道。 |
常用配置
| 成员或参数 | 作用和条件 |
| args | 优先使用参数序列,Shell 模式的固定命令通常写成字符串。 |
| stdin | PIPE 供调用者写入,None 继承输入句柄。 |
| stdout | 可选 PIPE、文件句柄、DEVNULL 或 None。 |
| stderr | 可独立 PIPE,或设 STDOUT 合流。 |
| shell | 默认为 False。True 启动平台 Shell 并解析文本。 |
| cwd | 子进程的工作目录。 |
| env | 为子进程提供环境映射。需要继承时复制原环境后修改。 |
| timeout | 用于 run、wait、communicate 等调用,不是 Popen 构造参数。 |
| text | 为真时使用文本流,可结合 encoding 固定编码。 |
本章自编源码与运行范围
展开查看收起
"""Exercise subprocess with fixed, locally owned commands and data."""
import json
import os
import queue
import subprocess as sp
import sys
from pathlib import Path
from tempfile import TemporaryDirectory
from threading import Thread
def command(source, *args):
return [sys.executable, "-I", "-B", "-X", "utf8", "-c", source, *args]
def observe():
checks = []
def check(name, actual, expected, inputs, operation):
if actual != expected:
raise AssertionError((name, actual, expected))
checks.append(dict(name=name, input=inputs, operation=operation, expected=expected, actual=actual, passed=True))
def cleanup(process):
if process.poll() is None:
process.kill()
process.communicate(timeout=5)
text_mode = dict(text=True, encoding="utf-8")
names = ["灯 塔", "观察&记录", 'a"b']
argv_command = command("import json,sys;print(json.dumps(sys.argv[1:]))", *names)
done = sp.run(argv_command, capture_output=True, check=True, timeout=5, **text_mode)
check("run completes and preserves literal arguments", [isinstance(done, sp.CompletedProcess), done.args == argv_command,
done.returncode, json.loads(done.stdout), done.stderr], [True, True, 0, names, ""],
names, "Pass separate list elements without a shell and inspect CompletedProcess")
fixed = command("print('ready')")
raw = sp.run(fixed, capture_output=True, check=True, timeout=5)
check("binary stdout and stderr by default", [type(raw.stdout).__name__, raw.stdout.splitlines()[0].hex(), raw.stderr.hex()],
["bytes", "7265616479", ""], "ready", "Capture with binary defaults")
ready = sp.run(fixed, stdout=sp.DEVNULL, check=True, timeout=5)
check("uncaptured outputs are None", [ready.stdout, ready.stderr], [None, None], "stdout DEVNULL, stderr inherited",
"Read fields without capture")
filter_cmd = command("import sys\nfor line in sys.stdin:\n if 'harbor' in line:\n print(line.rstrip('\\n'))\nprint('checked', file=sys.stderr)")
filtered = sp.run(filter_cmd, input="yard\nharbor gate\nhill\n", capture_output=True, check=True, timeout=5, **text_mode)
check("text input filters exact output and diagnostics", [filtered.stdout, filtered.stderr],
["harbor gate\n", "checked\n"], "yard / harbor gate / hill", "Send text and capture both output streams")
merge = command("import sys;print('normal',flush=True);print('diagnostic',file=sys.stderr,flush=True)")
combined = sp.run(merge, stdout=sp.PIPE, stderr=sp.STDOUT, check=True, timeout=5, **text_mode)
check("STDOUT merges diagnostics", [combined.stdout, combined.stderr], ["normal\ndiagnostic\n", None],
"two ordered writes", "Redirect stderr into the stdout pipe")
fails = command("import sys;print('partial');print('failure',file=sys.stderr);sys.exit(7)")
ordinary = sp.run(fails, capture_output=True, timeout=5, **text_mode)
check("run default keeps nonzero status", [ordinary.returncode, ordinary.stdout, ordinary.stderr],
[7, "partial\n", "failure\n"], "child exits 7", "Run without check and inspect the result")
try:
sp.run(fails, capture_output=True, check=True, timeout=5, **text_mode)
except sp.CalledProcessError as exc:
check("checked run exception carries output", [exc.returncode, exc.stdout, exc.stderr],
[7, "partial\n", "failure\n"], "child exits 7", "Enable check=True and inspect exception fields")
with TemporaryDirectory(prefix="mbsky-subprocess-") as directory:
work = Path(directory)
absent = work / "missing-command.exe"
try:
sp.run([str(absent)], check=True, timeout=5)
except FileNotFoundError as exc:
check("missing executable fails to launch", type(exc).__name__, "FileNotFoundError",
absent.name, "Pass a nonexistent absolute executable path")
log = work / "output.txt"
with log.open("w", encoding="utf-8", newline="\n") as target:
sp.run(fixed, stdout=target, check=True, timeout=5)
check("stdout redirected into file", log.read_text(encoding="utf-8"), "ready\n",
"open local output.txt", "Redirect to the file, close it, and read the result")
original_note = os.environ.get("MBSKY_SUBPROCESS_NOTE")
env = os.environ.copy()
env["MBSKY_SUBPROCESS_NOTE"] = "sealed"
setup = command("import json,os;print(json.dumps([os.getcwd(),os.environ['MBSKY_SUBPROCESS_NOTE']]))")
proc = sp.run(setup, cwd=work, env=env, capture_output=True, check=True, timeout=5, **text_mode)
cwd, label = json.loads(proc.stdout)
check("cwd and env observed in child", [Path(cwd).resolve() == work.resolve(), label], [True, "sealed"],
"temporary directory and one child-only environment key", "Read current directory and supplied environment in the child")
check("parent environment preserved", os.environ.get("MBSKY_SUBPROCESS_NOTE") == original_note
and env["MBSKY_SUBPROCESS_NOTE"] == "sealed", True, "environment dictionary copied",
"Check the child environment dictionary without assigning into os.environ")
inherit = command("import subprocess,sys;subprocess.run([sys.executable,'-I','-c',"
"'import sys;print(sys.stdin.readline().strip())'],stdin=None,check=True)")
inherited = sp.run(inherit, input="carried\n", capture_output=True, check=True, timeout=5, **text_mode)
check("stdin None inherits parent handle", inherited.stdout, "carried\n", "a pipe held by the intermediary",
"The intermediary leaves stdin=None while the grandchild reads the inherited handle")
check("call returns nonzero status", sp.call(fails, stdout=sp.DEVNULL, stderr=sp.DEVNULL, timeout=5), 7,
"child exits 7", "Read status using the historical call API")
check("check_call returns zero on success", sp.check_call(fixed, stdout=sp.DEVNULL, timeout=5), 0,
"successful child", "Run historical check_call")
try:
sp.check_call(fails, stdout=sp.DEVNULL, stderr=sp.DEVNULL, timeout=5)
except sp.CalledProcessError as exc:
check("check_call raises on nonzero", exc.returncode, 7, "child exits 7", "Inspect CalledProcessError from check_call")
check("check_output returns bytes", sp.check_output(fixed, timeout=5).splitlines()[0].hex(), "7265616479",
"successful child", "Capture the historical check_output result as bytes")
check("check_output returns text in text mode", sp.check_output(fixed, timeout=5, **text_mode), "ready\n",
"successful child with UTF-8", "Capture the historical check_output result as text")
try:
sp.check_output(fails, stderr=sp.PIPE, timeout=5, **text_mode)
except sp.CalledProcessError as exc:
check("check_output raises with captured streams", [exc.returncode, exc.stdout, exc.stderr],
[7, "partial\n", "failure\n"], "child exits 7", "Inspect output carried by historical check_output")
with sp.Popen(filter_cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE, **text_mode) as proc:
try:
piped = all(stream is not None for stream in (proc.stdin, proc.stdout, proc.stderr))
output, diagnostics = proc.communicate(input="harbor pier\nroad\n", timeout=5)
check("communicate transfers input and drains both pipes", [piped, output, diagnostics, proc.returncode],
[True, "harbor pier\n", "checked\n", 0], "all three PIPE streams", "Send input and drain both outputs before exit")
finally:
if proc.poll() is None:
cleanup(proc)
produce = command("print('pier 17');print('road 3');print('pier 8')")
consume = command("import sys; print(sum(1 for line in sys.stdin if line.startswith('pier ')))")
with sp.Popen(produce, stdout=sp.PIPE) as producer:
try:
with sp.Popen(consume, stdin=producer.stdout, stdout=sp.PIPE, stderr=sp.PIPE, **text_mode) as consumer:
producer.stdout.close()
try:
output, diagnostics = consumer.communicate(timeout=5)
finally:
if consumer.poll() is None:
cleanup(consumer)
check("explicit pipeline closes parent copy and reaps both", [producer.stdout.closed, producer.wait(timeout=5),
consumer.returncode, output, diagnostics], [True, 0, 0, "2\n", ""],
"three producer lines, two matching", "Connect real processes without a shell and wait for both")
finally:
if producer.poll() is None:
producer.kill()
producer.wait(timeout=5)
stream_cmd = command("import sys; print('first',flush=True); sys.stdin.readline(); print('second',flush=True)")
with sp.Popen(stream_cmd, stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.DEVNULL, **text_mode) as proc:
lines = queue.Queue()
def read_lines():
for line in proc.stdout:
lines.put(line)
reader = Thread(target=read_lines, daemon=True)
reader.start()
try:
first = lines.get(timeout=5)
before = proc.poll()
proc.stdin.write("next\n")
proc.stdin.flush()
second = lines.get(timeout=5)
status = proc.wait(timeout=5)
check("stream line observed before exit", [first, before, second, status, proc.poll()],
["first\n", None, "second\n", 0, 0], "child waits for acknowledgement",
"Read flushed output, poll, send acknowledgement, read second line, and wait")
finally:
if proc.poll() is None:
proc.kill()
proc.wait(timeout=5)
reader.join(timeout=5)
shell_text = "echo first&&echo second" if os.name == "nt" else "printf 'first\\n'; printf 'second\\n'"
shell_run = sp.run(shell_text, shell=True, capture_output=True, check=True, timeout=5, **text_mode)
check("fixed shell compound command", [shell_run.stdout, shell_run.returncode],
["first\nsecond\n", 0], "fixed command text with a shell operator", "Start the platform shell and run two built-in commands")
if os.name == "nt":
findstr = Path(os.environ["SystemRoot"]) / "System32" / "findstr.exe"
shell_pipe = f'echo harbor|"{findstr}" /x harbor'
else:
shell_pipe = "printf 'harbor\\n' | grep -x harbor"
selected = sp.run(shell_pipe, shell=True, capture_output=True, check=True, timeout=5, **text_mode)
check("fixed shell pipe feeds its second command", [selected.stdout, selected.returncode], ["harbor\n", 0],
"fixed text sent to the system filter", "Run a known shell pipeline and capture its matching line")
sleeper = command("import time;time.sleep(10)")
try:
sp.run(sleeper, timeout=0.15, stdout=sp.DEVNULL, stderr=sp.DEVNULL)
except sp.TimeoutExpired as exc:
check("run timeout raises and returns control", round(exc.timeout, 3), 0.15, "fixed 10-second child and 0.15-second limit",
"Run with a timeout and record TimeoutExpired timeout rounded to milliseconds")
with sp.Popen(sleeper, stdout=sp.PIPE, stderr=sp.PIPE, **text_mode) as proc:
try:
proc.communicate(timeout=0.15)
except sp.TimeoutExpired:
still_alive = proc.poll() is None
proc.kill()
result = proc.communicate(timeout=5)
check("Popen timeout requires explicit reap", [still_alive, proc.returncode is not None, list(result)],
[True, True, ["", ""]], "Popen sleeper and bounded communicate", "After timeout kill owned child, drain pipes and reap")
finally:
if proc.poll() is None:
cleanup(proc)
with sp.Popen(sleeper, stdout=sp.DEVNULL, stderr=sp.DEVNULL) as proc:
try:
proc.wait(timeout=0.15)
except sp.TimeoutExpired:
check("Popen wait timeout leaves child running", proc.poll(), None, "owned sleeper with bounded wait",
"Wait for a short limit, then check the child is still running")
finally:
if proc.poll() is None:
proc.kill()
proc.wait(timeout=5)
for method, signal_code in (("terminate", -15), ("kill", -9)):
with sp.Popen(sleeper, stdout=sp.DEVNULL, stderr=sp.DEVNULL) as proc:
try:
getattr(proc, method)()
status = proc.wait(timeout=5)
check(method + " stops owned child", status, 1 if os.name == "nt" else signal_code,
"owned sleeping Python process", "Call " + method + " and collect platform exit status")
finally:
if proc.poll() is None:
cleanup(proc)
required = {"checked run exception carries output", "missing executable fails to launch", "check_call raises on nonzero",
"run timeout raises and returns control", "Popen timeout requires explicit reap",
"check_output raises with captured streams", "Popen wait timeout leaves child running"}
if not required.issubset(row["name"] for row in checks):
raise AssertionError("a required failure did not occur")
return checks
if __name__ == "__main__":
print(json.dumps(observe(), ensure_ascii=True, indent=2))
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
本章附件与实例包
常见错误与边界检查
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
技术规范与官方资料
练习与参考解答
查看参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。