跳到主要内容
版本:1.2.2

redirect_stdout

私有上下文源码

with redirect_stdout(target: SupportsWrite):
...

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

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

提示

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

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

别名

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

import syncstream


syncstream.redirect_stdout
syncstream.base.redirect_stdouts

参数

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

范例

将stdout重定向到缓存

use_this_function.py
import syncstream
from syncstream.base import redirect_stdout


buffer = syncstream.LineBuffer(10)
with redirect_stdout(buffer):
for i in range(20):
print(f'Message "{i:02d}".')
print('No line break.', end='')

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