Python contextlib.redirect_stdout / redirect_stderr:捕获范围、嵌套恢复与全局副作用
给旧函数补一层输出捕获时,最容易把“替换 Python 流对象”误解为“接管整个程序的输出”。contextlib.redirect_stdout 适合短小、受控的脚本片段;先明确谁在写、写向哪个对象,再决定能否捕获。本文用可独立运行的例子解释 stderr、嵌套恢复、保存引用与子进程边界。

一、返回的是目标流,两个通道分别处理
进入 with 后,as 变量就是传入的目标对象,不是管理器,也不是捕获到的字符串。要取得文本,应在块外调用 StringIO.getvalue()。默认 print,以及 file=None,查询当时的 sys.stdout;显式 file 参数则决定具体目标。redirect_stdout 不顺带修改 sys.stderr,需要两个通道时分别重定向。依据:contextlib 文档、print 文档。
import sys
from contextlib import redirect_stdout, redirect_stderr
from io import StringIO
out, err = StringIO(), StringIO()
with redirect_stdout(out) as target, redirect_stderr(err):
print("job", 7)
print("retry", file=sys.stderr)
print(target is out)
print(repr(out.getvalue()))
print(repr(err.getvalue()))预期输出:
True 'job 7\n' 'retry\n'
二、恢复的是上一层,不一定是终端
内层退出后应回到外层目标,最外层退出才回到进入前的对象。下面的异常不会被重定向管理器吞掉;内层先恢复,再由外层代码捕获,于是 C 进入 outer。不要用 sys.__stdout__ 代替“上一层”,否则会绕过测试框架或宿主已有的捕获。
import sys
from contextlib import redirect_stdout
from io import StringIO
old = sys.stdout
outer, inner = StringIO(), StringIO()
with redirect_stdout(outer):
print("A")
try:
with redirect_stdout(inner):
print("B")
raise ValueError("demo")
except ValueError:
print("C")
print(sys.stdout is old)
print(repr(outer.getvalue()))
print(repr(inner.getvalue()))预期输出:
True 'A\nC\n' 'B\n'
已核对的 CPython 3.12.14 源码与 3.13.5 源码在每次进入时保存旧目标,退出时按栈弹出恢复。因此同一管理器既能先后复用,也能在自身作用域内再次进入。构造管理器时尚未替换流;保存旧流发生在进入时。它也不负责关闭或主动刷新借来的目标,这些生命周期仍由调用者管理。
三、旧引用不会跟着属性替换走
给 sys.stdout 重新赋值不会改写其他变量。提前保存的流,或它的 write 绑定方法,仍指向原对象。下面用内存流模拟原目标,避免向真实终端额外写入。相反,辅助函数若执行普通 print,会在调用时看到当前全局流,而不受函数定义位置限制。
import sys
from contextlib import redirect_stdout
from io import StringIO
previous, capture = StringIO(), StringIO()
with redirect_stdout(previous):
saved = sys.stdout
with redirect_stdout(capture):
print("current")
print("explicit", file=saved)
print(repr(capture.getvalue()))
print(repr(previous.getvalue()))预期输出:
'current\n' 'explicit\n'
四、可重入不等于并发隔离
嵌套栈解决顺序进入与退出,不会把 sys.stdout 变成线程局部变量。其他代码在作用域内读取它,也会看见替换后的对象。官方明确提醒,这类全局副作用不适合通用库及多数多线程应用。新接口优先接收输出流参数,或返回结果交给调用方展示;不要仅凭一个锁就宣称所有写入都安全。本文只做单线程验证,没有并发改写实验。参见可重入与线程安全的区别。
五、文本、二进制与子进程各有边界
StringIO 接收 str,不接收 bytes,也没有 buffer 属性;BytesIO 则不能直接接收 print 生成的文本。已有二进制缓冲区的显式写入仍去那个缓冲区。不要假设替代流总有终端流的全部接口,详见 sys 标准流说明。
替换父进程的 sys.stdout 也不会捕获子进程输出。用 subprocess 的 stdout、stderr 参数管理子进程通道。套件第 33 项启动本地小程序,并显式设置两个 PIPE:父级捕获只得到 parent,子级文本从返回对象单独取出。PIPE 是安全收集子输出的对照,不是对继承终端路径的实测;一般边界来自官方文档。子程序不联网、不写文件。参见 subprocess.run。
六、完整可复制验证套件
以下代码可单独保存为 suite.py,用 python suite.py 与 python -O suite.py 运行。预期值是执行前按契约写定的字面量,不由被测函数生成;失败直接抛 RuntimeError,不依赖会被优化移除的 assert。七个故意错误的包装器分别检验返回值、恢复目标、异常清理、重入栈、通道隔离、目标所有权及保存时机,只供反例测试。
北京时间 2026 年 10 月 22 日 09:01 冻结后首次运行:CPython 3.12.14、3.13.5 各自普通与 -O 模式,四组均通过 36 项检查、区分 7 个错误包装器;上面三个短例也分别通过四组。首次记录无意外结果,未改预期。在线文档页目前显示的补丁版本并非本次实测版本;这些结果不外推为所有解释器、线程或底层文件描述符的保证。
展开或收起完整套件,含固定预期与错误包装器反例
"""Self-contained checks: python suite.py and python -O suite.py."""
import io
import json
import platform
import subprocess
import sys
from contextlib import contextmanager, redirect_stdout, redirect_stderr
ORACLE = {
"01_stdout_enter": True,
"02_stderr_enter": True,
"03_print_default": "hello\n",
"04_print_none": "none\n",
"05_stdout_write": [3, "abc"],
"06_stderr_write": [3, "err"],
"07_stdout_only": ["out\n", "err\n"],
"08_stderr_only": ["out\n", "err\n"],
"09_explicit_file": ["", "other\n"],
"10_saved_stream": ["", "saved\n"],
"11_saved_method": ["", "bound"],
"12_global_lookup": "helper\n",
"13_stdout_nested": ["A\nC\n", "B\n", True],
"14_stderr_nested": ["A\nC\n", "B\n", True],
"15_stdout_exception": [True, True, "before\n"],
"16_stderr_exception": [True, True, "before\n"],
"17_inner_exception": [True, "after\n", "inside\n"],
"18_unwind_both": [True, True],
"19_stdout_reuse": ["one\ntwo\n", True],
"20_stdout_reenter": ["one\ntwo\nthree\n", True],
"21_stderr_reuse": ["one\ntwo\n", True],
"22_stderr_reenter": ["one\ntwo\nthree\n", True],
"23_target_open": [False, "more"],
"24_exception_target_open": False,
"25_no_auto_flush": ["x\n", 0],
"26_explicit_flush": ["x\n", 1],
"27_unicode_format": "云|7!",
"28_bytes_to_text": "TypeError",
"29_missing_buffer": "AttributeError",
"30_text_to_bytes": "TypeError",
"31_custom_sink": "custom\n",
"32_explicit_stderr": "explicit\n",
"33_child_control": ["parent\n", "child-out\n", "child-err\n", 0],
"34_explicit_buffer": ["", "binary"],
"35_restore_previous": [True, True],
"36_entry_timing": [True, True, "entered\n"],
}
WITNESS_ORACLE = {
"return_target": [True, False],
"restore_previous": [True, False],
"restore_on_error": [True, False],
"reenter_stack": [True, False],
"stdout_not_stderr": ["", "err\n"],
"leave_target_open": [False, True],
"save_at_entry": [True, False],
}
def check(name, got, expected):
if got != expected:
raise RuntimeError(f"{name}: got {got!r}, expected {expected!r}")
class Sink:
def __init__(self):
self.parts = []
self.flushes = 0
def write(self, text):
self.parts.append(text)
return len(text)
def flush(self):
self.flushes += 1
def value(self):
return "".join(self.parts)
def collect_cases():
got = {}
for name, factory in [("01_stdout_enter", redirect_stdout),
("02_stderr_enter", redirect_stderr)]:
target = io.StringIO()
with factory(target) as entered:
got[name] = entered is target
for name, file_none in [("03_print_default", False),
("04_print_none", True)]:
target = io.StringIO()
with redirect_stdout(target):
if file_none:
print("none", file=None)
else:
print("hello")
got[name] = target.getvalue()
for name, stream, factory, text in [
("05_stdout_write", "stdout", redirect_stdout, "abc"),
("06_stderr_write", "stderr", redirect_stderr, "err")]:
target = io.StringIO()
with factory(target):
count = getattr(sys, stream).write(text)
got[name] = [count, target.getvalue()]
out, err = io.StringIO(), io.StringIO()
with redirect_stderr(err):
with redirect_stdout(out):
print("out")
print("err", file=sys.stderr)
got["07_stdout_only"] = [out.getvalue(), err.getvalue()]
out, err = io.StringIO(), io.StringIO()
with redirect_stdout(out):
with redirect_stderr(err):
print("out")
print("err", file=sys.stderr)
got["08_stderr_only"] = [out.getvalue(), err.getvalue()]
target, other = io.StringIO(), io.StringIO()
with redirect_stdout(target):
print("other", file=other)
got["09_explicit_file"] = [target.getvalue(), other.getvalue()]
for name, bound in [("10_saved_stream", False),
("11_saved_method", True)]:
target, previous = io.StringIO(), io.StringIO()
with redirect_stdout(previous):
saved = sys.stdout
saved_write = sys.stdout.write
with redirect_stdout(target):
if bound:
saved_write("bound")
else:
print("saved", file=saved)
got[name] = [target.getvalue(), previous.getvalue()]
def helper():
print("helper")
target = io.StringIO()
with redirect_stdout(target):
helper()
got["12_global_lookup"] = target.getvalue()
for name, stream, factory in [
("13_stdout_nested", "stdout", redirect_stdout),
("14_stderr_nested", "stderr", redirect_stderr)]:
old = getattr(sys, stream)
outer, inner = io.StringIO(), io.StringIO()
with factory(outer):
print("A", file=getattr(sys, stream))
with factory(inner):
print("B", file=getattr(sys, stream))
print("C", file=getattr(sys, stream))
got[name] = [outer.getvalue(), inner.getvalue(),
getattr(sys, stream) is old]
for name, stream, factory in [
("15_stdout_exception", "stdout", redirect_stdout),
("16_stderr_exception", "stderr", redirect_stderr)]:
old, target = getattr(sys, stream), io.StringIO()
error, caught = ValueError("sentinel"), False
try:
with factory(target):
print("before", file=getattr(sys, stream))
raise error
except ValueError as exc:
caught = exc is error
got[name] = [caught, getattr(sys, stream) is old, target.getvalue()]
outer, inner = io.StringIO(), io.StringIO()
with redirect_stdout(outer):
try:
with redirect_stdout(inner):
print("inside")
raise LookupError("sentinel")
except LookupError:
restored_outer = sys.stdout is outer
print("after")
got["17_inner_exception"] = [restored_outer, outer.getvalue(), inner.getvalue()]
old_out, old_err = sys.stdout, sys.stderr
try:
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
raise ValueError("sentinel")
except ValueError:
pass
got["18_unwind_both"] = [sys.stdout is old_out, sys.stderr is old_err]
for name, stream, factory, nested in [
("19_stdout_reuse", "stdout", redirect_stdout, False),
("20_stdout_reenter", "stdout", redirect_stdout, True),
("21_stderr_reuse", "stderr", redirect_stderr, False),
("22_stderr_reenter", "stderr", redirect_stderr, True)]:
old, target = getattr(sys, stream), io.StringIO()
manager = factory(target)
with manager:
print("one", file=getattr(sys, stream))
if nested:
with manager:
print("two", file=getattr(sys, stream))
print("three", file=getattr(sys, stream))
if not nested:
with manager:
print("two", file=getattr(sys, stream))
got[name] = [target.getvalue(), getattr(sys, stream) is old]
target = io.StringIO()
with redirect_stdout(target):
pass
target.write("more")
got["23_target_open"] = [target.closed, target.getvalue()]
target = io.StringIO()
try:
with redirect_stdout(target):
raise ValueError("sentinel")
except ValueError:
pass
got["24_exception_target_open"] = target.closed
for name, flush in [("25_no_auto_flush", False), ("26_explicit_flush", True)]:
target = Sink()
with redirect_stdout(target):
print("x", flush=flush)
got[name] = [target.value(), target.flushes]
target = io.StringIO()
with redirect_stdout(target):
print("云", 7, sep="|", end="!")
got["27_unicode_format"] = target.getvalue()
for name, target, action in [
("28_bytes_to_text", io.StringIO(), lambda: sys.stdout.write(b"x")),
("29_missing_buffer", io.StringIO(), lambda: sys.stdout.buffer),
("30_text_to_bytes", io.BytesIO(), lambda: print("x"))]:
kind = "no exception"
try:
with redirect_stdout(target):
action()
except (TypeError, AttributeError) as exc:
kind = type(exc).__name__
got[name] = kind
target = Sink()
with redirect_stdout(target):
print("custom")
got["31_custom_sink"] = target.value()
target = io.StringIO()
with redirect_stderr(target):
print("explicit", file=sys.stderr)
got["32_explicit_stderr"] = target.getvalue()
target = io.StringIO()
child = "import sys; print('child-out'); print('child-err', file=sys.stderr)"
with redirect_stdout(target):
print("parent")
result = subprocess.run(
[sys.executable, "-I", "-S", "-B", "-c", child],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, encoding="utf-8", check=True, timeout=10)
got["33_child_control"] = [target.getvalue(), result.stdout, result.stderr,
result.returncode]
raw, target = io.BytesIO(), io.StringIO()
wrapper = io.TextIOWrapper(raw, encoding="utf-8")
try:
with redirect_stdout(target):
wrapper.buffer.write(b"binary")
got["34_explicit_buffer"] = [target.getvalue(), raw.getvalue().decode("ascii")]
finally:
wrapper.detach()
raw.close()
old, previous = sys.stdout, io.StringIO()
with redirect_stdout(previous):
with redirect_stdout(io.StringIO()):
pass
restored_previous = sys.stdout is previous
got["35_restore_previous"] = [restored_previous, sys.stdout is old]
old, previous, target = sys.stdout, io.StringIO(), io.StringIO()
manager = redirect_stdout(target)
unchanged = sys.stdout is old
with redirect_stdout(previous):
with manager:
print("entered")
restored_at_entry = sys.stdout is previous
got["36_entry_timing"] = [unchanged, restored_at_entry, target.getvalue()]
return got
class WrongReturn:
def __init__(self, target):
self.target = target
def __enter__(self):
self.old = sys.stdout
sys.stdout = self.target
return self
def __exit__(self, *exc):
sys.stdout = self.old
class WrongOriginal(WrongReturn):
def __exit__(self, *exc):
sys.stdout = sys.__stdout__
@contextmanager
def wrong_exception(target):
old = sys.stdout
sys.stdout = target
yield target
sys.stdout = old # Missing finally: exception skips this line.
class WrongSlot(WrongReturn):
pass # Only one old-stream slot, overwritten on nested entry.
@contextmanager
def wrong_both(target):
with redirect_stdout(target), redirect_stderr(target):
yield target
@contextmanager
def wrong_close(target):
try:
with redirect_stdout(target):
yield target
finally:
target.close()
class WrongEarly(WrongReturn):
def __init__(self, target):
super().__init__(target)
self.old = sys.stdout
def __enter__(self):
sys.stdout = self.target
return self.target
def probe(kind, factory):
original_out, original_err = sys.stdout, sys.stderr
baseline, target = io.StringIO(), io.StringIO()
try:
if kind == "save_at_entry":
manager = factory(target)
sys.stdout = baseline
else:
sys.stdout = baseline
manager = factory(target)
if kind == "return_target":
with manager as entered:
return entered is target
if kind == "restore_previous":
with manager:
pass
return sys.stdout is baseline
if kind == "restore_on_error":
try:
with manager:
raise ValueError("sentinel")
except ValueError:
pass
return sys.stdout is baseline
if kind == "reenter_stack":
with manager:
with manager:
pass
return sys.stdout is baseline
if kind == "stdout_not_stderr":
sys.stderr = io.StringIO()
with manager:
print("err", file=sys.stderr)
return target.getvalue()
if kind == "leave_target_open":
with manager:
pass
return target.closed
if kind == "save_at_entry":
with manager:
pass
return sys.stdout is baseline
raise RuntimeError("unknown probe")
finally:
sys.stdout, sys.stderr = original_out, original_err
def main():
initial_out, initial_err = sys.stdout, sys.stderr
try:
observations = collect_cases()
check("case names", sorted(observations), sorted(ORACLE))
for name, expected in ORACLE.items():
check(name, observations[name], expected)
bad_factories = {
"return_target": WrongReturn,
"restore_previous": WrongOriginal,
"restore_on_error": wrong_exception,
"reenter_stack": WrongSlot,
"stdout_not_stderr": wrong_both,
"leave_target_open": wrong_close,
"save_at_entry": WrongEarly,
}
witnesses = {}
for name, bad in bad_factories.items():
values = [probe(name, redirect_stdout), probe(name, bad)]
check(name, values, WITNESS_ORACLE[name])
if values[0] == values[1]:
raise RuntimeError(f"witness failed to distinguish: {name}")
witnesses[name] = values
finally:
sys.stdout, sys.stderr = initial_out, initial_err
print(json.dumps({"python": platform.python_version(),
"implementation": platform.python_implementation(),
"optimize": sys.flags.optimize,
"cases_passed": len(observations),
"wrong_wrappers_rejected": len(witnesses),
"observations": observations, "witnesses": witnesses},
ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()遇到漏捕获时,先查显式 file 与旧引用,再查是否写二进制缓冲区或来自子进程;不要先扩大重定向范围。能控制接口时,把输出目标显式传进去,通常比修改全局流更容易组合和测试。

