Python sys:命令行、标准流与解释器状态
在子进程检查参数、标准流和退出码,在当前解释器观察导入路径、对象大小、递归限制及跟踪事件。
学完这一章,你能够
- 在子进程检查参数、标准流和退出码,在当前解释器观察导入路径、对象大小、递归限制及跟踪事件。
检查 sys 与真实启动参数
sys 随解释器提供,直接 import sys。要看其成员可用 dir(sys)。仅导入 sys 后使用 dir(os) 会引用未绑定的名字。sys.modules 保存已导入模块,重复导入一般先命中缓存。
运行 python gauge.py 北窗 7 时,本实验中 argv[0] 为 gauge.py,argv[1:] 是两个字符串。argv[0] 由启动方式决定,文件启动也可能给出完整路径,-c 启动时为 -c。
观察退出状态和三条标准流
sys.exit() 抛出 SystemExit。主线程未捕获时会终止进程,仍会运行 finally。None 或整数 0 表示成功,非零整数可用作错误状态。传入字符串时,解释器通常将它写到 stderr 并以状态 1 退出。用子进程观察退出码和退出前的输出。
stdin 读数据,stdout 写正常结果,stderr 写诊断。用 subprocess 捕获时分别取 stdout 和 stderr,不混入同一条结果。默认文本编码和标准流实际编码分别查看。
临时改写 stdout 可用 redirect_stdout,退出上下文恢复进入前的实际流。写文件时使用嵌套 with,让流先恢复、文件再关闭。sys.__stdout__ 是解释器启动时的原始流,未必是调用前的重定向目标。Python 流的临时重定向影响整个进程,并不接管已启动子进程的流。
比较版本、路径和平台数据
sys.version 用于显示,程序判断版本用 sys.version_info 的 major、minor 和 micro。3.9.7 是历史版本输出,当前实例读取自己的解释器版本。sys.executable 在能取得时是解释器路径,可能为空或为 None。Windows 的 sys.platform 通常为 win32,即使解释器是 64 位。
sys.path 是导入搜索路径。启动目录、环境中的 PYTHONPATH、安装位置及隔离选项都可能影响它。实验先确认临时模块不可见,再附加临时目录、导入并移除目录。即使移除路径,已导入的模块仍可从 sys.modules 命中。实验结束会恢复路径和缓存。
sys.byteorder 指本机整数的字节顺序。sys.maxsize 是 Py_ssize_t 上限,与指针宽度有关。Python int 可以超过这个数,例如 sys.maxsize + 1。示例用本机字节和实际整数计算验证。
观察对象大小、异常和回调
sys.getsizeof 给对象自身的浅层字节大小,容器引用的子对象要另算。不可测时可指定 default。sys.getrefcount 是 CPython 的诊断接口,调用时多一个临时引用。3.12 的永生对象可能显示与实际引用量无关的大数,本例只比较普通对象新增一个别名后的差值。
通过 getrecursionlimit 读取当前限制,再有限调整并恢复。把限制设到当前调用深度以下会引发 RecursionError。默认数值和最高安全值依平台与环境,不能通过任意提高限制来修复无限递归。sys.exc_info 在处理异常时返回类型、异常对象和回溯,无当前异常时返回三个 None。
settrace 与 setprofile 设置当前线程的回调,传 None 可撤销。跟踪回调可观察 Python 行,调用事件返回的局部跟踪函数决定后续事件。性能分析回调关注 Python/C 调用和返回,其返回值不参与后续调度。实验在 finally 恢复先前回调。
下载实验 ZIP,解压后执行 python python-sys.py。查看每条记录的输入、操作、预期和实际值。实验仅用标准库和临时文件,退出码由子进程产生。
所需环境:CPython 3.12 标准库
ZIP SHA256:7e2b5aad251d9de6dee7f824a3c6c9d3603931bc3b3db7884b671c60580d2a2c
解释器状态与标准流
| 成员 | 作用和限制 |
|---|---|
| sys.argv | 字符串列表,索引 0 随启动方式变化,后续是传给程序的参数。 |
| sys.path | 模块搜索路径列表,启动模式、环境与安装位置可参与初始化。 |
| sys.modules | 已导入模块的缓存字典,键是模块名。 |
| sys.platform | 平台标识字符串,如 win32、linux、darwin。 |
| sys.version | 解释器版本与构建信息的显示字符串。数值比较用 version_info。 |
| sys.executable | 已知时为解释器的绝对路径,无法取得时可能为空或为 None。 |
| sys.stdin | 标准输入文本流,可从管道读取。 |
| sys.stdout | 标准输出文本流,print 默认写入这里。 |
| sys.stderr | 标准错误文本流,可与 stdout 分别重定向。 |
| sys.byteorder | 本机字节顺序,取 little 或 big。 |
| sys.maxsize | Py_ssize_t 的上限。通常是 2**31-1 或 2**63-1,int 可超过。 |
退出、诊断及跟踪接口
| 成员 | 作用和限制 |
|---|---|
| sys.exit([status]) | 抛出 SystemExit。未捕获时 None/0 对应成功,整数给退出码,字符串写入错误流并通常退出为 1。 |
| sys.getsizeof(obj, default) | 返回对象自身字节数,缺少大小实现时可使用 default。 |
| sys.getdefaultencoding() | 返回解释器默认文本编码,当前 CPython 为 utf-8。 |
| sys.setrecursionlimit(limit) | 接收整数限制并修改当前设置。低于活动栈深度时抛 RecursionError。 |
| sys.getrecursionlimit() | 读取当前递归限制的整数。 |
| sys.getrefcount(obj) | CPython 返回引用计数诊断值。包含本次调用的临时引用,永生对象需另解。 |
| sys.exc_info() | 返回 (异常类型, 异常对象, traceback),没有正在处理的异常时三项均为 None。 |
| sys.settrace(tracefunc) | 接收 (frame, event, arg) 的跟踪回调,局部回调由返回值决定,None 可停用。 |
| sys.setprofile(profilefunc) | 接收 (frame, event, arg) 的性能回调,返回值被忽略,None 可停用。 |
本章自编源码与运行范围
"""Observe Python interpreter state without changing the calling shell."""
import importlib
import importlib.util
import io
import json
import platform
import struct
import subprocess
import sys
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import uuid4
def observe():
checks = []
def check(name, actual, expected, inputs, operation):
if actual != expected:
raise AssertionError((name, actual, expected))
checks.append(dict(name=name, actual=actual, expected=expected, input=inputs,
operation=operation, passed=True))
def child(source, *args, stdin=""):
return subprocess.run(
[sys.executable, "-I", "-B", "-X", "utf8", "-c", source, *args],
input=stdin, capture_output=True, encoding="utf-8", timeout=10,
)
check("sys namespace", ["argv" in dir(sys), "exit" in dir(sys), sys is importlib.import_module("sys")],
[True, True, True], "sys", "Inspect dir(sys) and reimport sys")
check("module cache identity", sys.modules["sys"] is sys, True, "sys.modules['sys']",
"Compare the cached module and local binding by identity")
check("script argv and user arguments", json.loads(child(
"import sys,json; print(json.dumps(sys.argv))", "北窗", "7").stdout),
["-c", "北窗", "7"], ["北窗", "7"], "Launch -c and read the real argument list")
with TemporaryDirectory(prefix="mbsky-sys-") as work:
root = Path(work)
script = root / "gauge.py"
script.write_text("import sys, json\nprint(json.dumps(sys.argv))\n", encoding="utf-8")
proc = subprocess.run([sys.executable, "-B", "-X", "utf8", script.name, "北窗", "7"],
cwd=root, capture_output=True, encoding="utf-8", timeout=10, check=True)
check("file argv zero", json.loads(proc.stdout), ["gauge.py", "北窗", "7"], "gauge.py 北窗 7",
"Run a script by its relative name and inspect argv[0]")
name = "mbsky_gauge_" + uuid4().hex
(root / f"{name}.py").write_text("READING = 18\n", encoding="utf-8")
before = list(sys.path)
check("module initially outside search path", importlib.util.find_spec(name) is None, True,
"owned module in a new temporary directory", "Ask the import machinery before adding the path")
try:
sys.path.append(str(root))
imported = importlib.import_module(name)
check("added path locates new module", [imported.READING, Path(imported.__file__).parent == root],
[18, True], "append temporary directory", "Import module and inspect its value and origin")
sys.path.pop()
check("cached module remains available", importlib.import_module(name) is imported, True,
"remove directory while retaining cache", "Import the same module again")
finally:
sys.path[:] = before
sys.modules.pop(name, None)
sys.path_importer_cache.pop(str(root), None)
check("import state restored", [sys.path == before, name not in sys.modules], [True, True],
"after fixture cleanup", "Compare sys.path and cache membership")
original = sys.stdout
output = root / "reading.txt"
with output.open("w", encoding="utf-8", newline="\n") as stream:
with redirect_stdout(stream):
print("风向:北")
check("redirected UTF-8 bytes and restored stdout",
[output.read_bytes().hex(), sys.stdout is original],
["e9a38ee59091efbc9ae58c970a", True], "redirect_stdout and owned UTF-8 file",
"Write a line, close it, and compare bytes and prior stream identity")
for status, expected in [("None", [0, "开始\n清理\n", ""]), ("0", [0, "开始\n清理\n", ""]),
("7", [7, "开始\n清理\n", ""]), ("'拒绝'", [1, "开始\n清理\n", "拒绝\n"])]:
proc = child("import sys\nprint('开始')\ntry:\n sys.exit(" + status +
")\nfinally:\n print('清理')\nprint('不会执行')\n")
check("exit status " + status, [proc.returncode, proc.stdout, proc.stderr], expected, status,
"Observe real exit code, skipped following statement, finally, and stderr")
try:
sys.exit(4)
except SystemExit as exc:
check("SystemExit catchable", [exc.code, isinstance(exc, Exception)], [4, False], "sys.exit(4)",
"Catch SystemExit without terminating the current process")
proc = child("import sys; text=sys.stdin.readline(); sys.stdout.write(text.upper()); "
"sys.stderr.write('记录\\n')", stdin="north\n")
check("stdin stdout stderr are separate", [proc.returncode, proc.stdout, proc.stderr],
[0, "NORTH\n", "记录\n"], "north followed by a newline", "Pipe text in and capture both streams")
previous = sys.stderr
captured = io.StringIO()
try:
with redirect_stderr(captured):
print("诊断", file=sys.stderr)
raise ValueError("fixture")
except ValueError:
pass
check("stderr restored after exception", [captured.getvalue(), sys.stderr is previous], ["诊断\n", True],
"temporary StringIO and ValueError", "Check restoration by identity after exception")
check("version fields and display", [isinstance(sys.version, str), len(sys.version) > 0,
tuple(sys.version_info[:3]) == tuple(map(int, platform.python_version_tuple()))],
[True, True, True], "current interpreter", "Inspect display string and numeric version fields independently")
check("interpreter executable", [Path(sys.executable).is_absolute(), Path(sys.executable).is_file()],
[True, True], "current interpreter with a known executable", "Check actual executable path and filesystem entry")
check("platform identifier", sys.platform, {"Windows": "win32", "Linux": "linux", "Darwin": "darwin"}[platform.system()],
platform.system(), "Compare the system identifier and sys.platform")
check("native byte order", struct.pack("=H", 0x1234).hex(),
"3412" if sys.byteorder == "little" else "1234", "unsigned short 0x1234", "Pack with native byte order")
check("maxsize and arbitrary precision", [sys.maxsize == (1 << (8 * struct.calcsize("n") - 1)) - 1,
(sys.maxsize + 1).bit_length() > sys.maxsize.bit_length()],
[True, True], "native signed size and maxsize + 1", "Measure ssize_t width and construct a larger Python int")
check("default text encoding", sys.getdefaultencoding(), "utf-8", "current CPython",
"Read getdefaultencoding without assuming stdio or file encoding")
empty = []
one_child = [bytearray(1000)]
check("getsizeof excludes referred object", [sys.getsizeof(one_child) > sys.getsizeof(empty),
sys.getsizeof(one_child) < sys.getsizeof(one_child[0])],
[True, True], "one list holding a large bytearray", "Compare shallow size of container and its referred object")
check("getsizeof fallback", sys.getsizeof(type("NoSize", (), {"__sizeof__": None})(), 17), 17,
"object with unavailable __sizeof__ and explicit default", "Call getsizeof with fallback")
old_limit = sys.getrecursionlimit()
try:
sys.setrecursionlimit(old_limit + 10)
check("recursion limit can be read after setting", sys.getrecursionlimit(), old_limit + 10,
old_limit + 10, "Set a bounded higher limit and read it back")
try:
sys.setrecursionlimit(1)
except RecursionError as exc:
check("recursion limit too low", [type(exc).__name__, sys.getrecursionlimit()],
["RecursionError", old_limit + 10], 1, "Try a limit below the active stack depth")
finally:
sys.setrecursionlimit(old_limit)
check("recursion limit restored", sys.getrecursionlimit(), old_limit, old_limit, "Read the original limit after cleanup")
target = object()
count_before = sys.getrefcount(target)
alias = target
check("ordinary CPython reference delta", [alias is target, sys.getrefcount(target) - count_before],
[True, 1], "ordinary object and a new alias", "Measure the count difference with the same call shape")
check("exc_info outside handler", list(sys.exc_info()), [None, None, None], "no active exception handler",
"Read the three returned positions")
try:
raise ValueError("reading")
except ValueError as caught:
kind, value, traceback = sys.exc_info()
check("exc_info inside handler", [kind is ValueError, value is caught, traceback is caught.__traceback__],
[True, True, True], "handled ValueError", "Compare exception type, identity, and traceback identity")
def inspect_reading():
reading = 19
return abs(reading - 20)
def events(set_hook, get_hook, restore_return):
seen = []
def hook(frame, event, arg):
if frame.f_code is inspect_reading.__code__:
seen.append(event)
return hook if restore_return else None
before = get_hook()
try:
set_hook(hook)
result = inspect_reading()
finally:
set_hook(before)
return result, seen, get_hook() is before
result, trace, restored = events(sys.settrace, sys.gettrace, True)
check("trace sees Python lines and return", [result, trace, restored],
[1, ["call", "line", "line", "return"], True], "single known Python function",
"Install a local trace callback and restore the prior callback")
result, profile, restored = events(sys.setprofile, sys.getprofile, False)
check("profile sees call return and C events", [result, profile, restored],
[1, ["call", "c_call", "c_return", "return"], True], "same function calls abs",
"Install a profile callback and restore it after collecting events")
return checks
if __name__ == "__main__":
print(json.dumps(observe(), ensure_ascii=True, indent=2))
所需环境:Real subprocess exit, stream, argv and native CPython debugger/import observations
当前源码 SHA256:4d7d8d8bfbde039ac837f98d023eb5263b0a839a7c3adf6762e70f4cdb5cafb7
当前源码有命名范围的实际运行记录;原文全部事实、其它平台和IDE界面仍待逐项验收。
常见错误与边界
- 命令、源码、当前解释器和具体平台分别核对,不能以单项运行推断整章验收。
练习与解答
使用本站实例修改一个条件,先写下预期,再实际运行。
展开参考解答
比较原始输出、修改后的输出及错误类型;未执行的平台和界面继续单列。