"""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 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Real subprocess exit, stream, argv and native CPython debugger/import observations
入口文件:projects/python-lab/python-sys.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python-sys.py,或下载右侧课程工程包。 - 确认本地已准备 Real subprocess exit, stream, argv and native CPython debugger/import observations。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202611a479.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip