蓝色天空网mbsky.com · 知识 · 实践 · 创造Python · 本地阅读预览
教程 / Python / 数据科学 / Python

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 副本,消费末级输出,最后等待两端并分别核对退出码。实例过滤三行并得到两条命中。

区分 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 是其别名。示例只管理自己启动的直接子进程。进程树、信号处理和其他平台须另核对。

解压本站 ZIP 后运行 python python-subprocess.py。查看逐项记录中的输入、操作、预期、实际值。实测仅使用本机临时文件、固定 Shell 命令和 Python 子进程。

下载本站 subprocess 实验 ZIP

所需环境:CPython 3.12 标准库

ZIP SHA256:6579efdd46ef56e5e5b53c904183100b730396b4d64abc085482d7074089b4ac

运行接口

成员或参数作用和条件
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 模式的固定命令通常写成字符串。
stdinPIPE 供调用者写入,None 继承输入句柄。
stdout可选 PIPE、文件句柄、DEVNULL 或 None。
stderr可独立 PIPE,或设 STDOUT 合流。
shell默认为 False。True 启动平台 Shell 并解析文本。
cwd子进程的工作目录。
env为子进程提供环境映射。需要继承时复制原环境后修改。
timeout用于 run、wait、communicate 等调用,不是 Popen 构造参数。
text为真时使用文本流,可结合 encoding 固定编码。

本章自编源码与运行范围

Python · 阅读源码
"""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))
运行本章核心实例

所需环境:Actual local process lifecycles, streams, environment, timeout and pipeline observations

当前源码 SHA256:32bd14aa7851ff41534490ca7a9debb00ab71bb8e63117b214067dfb81386c22

下载本站示例源码

当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。

常见错误与边界

  • 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。

练习与解答

使用本站实例修改一个条件,先写下预期,再实际运行。

展开参考解答

比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。

规范与官方依据