蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行本章核心实例

PYTHONActual local process lifecycles, streams, environment, timeout and pipeline observationspython-subprocess.py
python-subprocess.py230 行
"""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 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Actual local process lifecycles, streams, environment, timeout and pipeline observations

入口文件:projects/python-lab/python-subprocess.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 python-subprocess.py,或下载右侧课程工程包。
  2. 确认本地已准备 Actual local process lifecycles, streams, environment, timeout and pipeline observations。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip

下载课程关联工程包:Python

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a301.zip

下载课程关联工程包:Python

课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习