python中的简单流重定向。
redirect-streams的Python项目详细描述
说明
此项目提供python上下文管理器来帮助重定向多个 输出到缓冲区的形式(捕获输出)。
安装
$ pip install redirect-streams
基本用法
此项目最常见的用途是重定向stdout。
fromioimportBytesIO,SEEK_SET,TextIOWrapperfromosimportsystemfromsysimportstdoutfromredirect_streamsimportredirect_stdoutwithTextIOWrapper(BytesIO(),stdout.encoding)asbuffer:withredirect_stdout(buffer):print('this will be saved in the buffer')# code below won't work with stdlib's redirect_stdoutsystem('this will be saved in the buffer')buffer.seek(SEEK_SET)saved=buffer.read()print(saved)
有关其他上下文管理器和更多详细信息,请参阅 到documentation。