跳到主要内容
版本:1.2.2

redirect_stderr

私有上下文源码

with redirect_stderr(target: SupportsWrite):
...

contextlib.redirect_stderr经过特殊封装的版本。

该上下文允许syncstream.LineBuffer或其镜像用作重定向的目标,并不引起任何类型检查异常。

提示

该上下文可能是不需要使用的,因为形如LineBuffer的缓存、现在本身就已经是一个上下文了。

由于缓存上下文会同时令stdoutstderr重定向,若不想重定向stdout,有可能还是会需要用该上下文。

别名

该类可以按以下方式之一获取

import syncstream


syncstream.redirect_stderr
syncstream.base.redirect_stderr

参数

参数类型必选
说明
targetSupportsWrite支持write方法的可写缓存。

范例

将stderr重定向到缓存

use_this_function.py
import syncstream
from syncstream.base import redirect_stderr


buffer = syncstream.LineBuffer(10)
with redirect_stderr(buffer):
try:
raise TypeError("test-error!")
except Exception as exc:
print(exc, file=buffer)

messages = buffer.read()
for mitem in messages:
print(mitem)