将python标准输出重定向到临时文件
我知道: 我在问如何进行以下工作: [2]中的将python标准输出重定向到临时文件,python,stdout,Python,Stdout,我知道: 我在问如何进行以下工作: [2]中的:使用tempfile.NamedTemporaryFile()作为tmp: …:contextlib.redirect_stdout(tmp): …:打印('this') 哪些错误与: TypeError: a bytes-like object is required, not 'str' 从文档()中: 上下文管理器,用于将sys.stdout临时重定向到另一个文件或类似文件的对象 搜索给了我这个帖子:哪个声明: 向底层资源公开面向文件的A
:使用tempfile.NamedTemporaryFile()作为tmp:
…:contextlib.redirect_stdout(tmp):
…:打印('this')
哪些错误与:
TypeError: a bytes-like object is required, not 'str'
从文档()中:
上下文管理器,用于将sys.stdout临时重定向到另一个文件或类似文件的对象
搜索给了我这个帖子:哪个声明:
向底层资源公开面向文件的API(使用read()或write()等方法)的对象
这让我想到,也许以下方法会奏效:
[2]中的:使用tempfile.NamedTemporaryFile()作为tmp:
…:contextlib.redirect_stdout(tmp.file):
…:打印('this')
由于tmp.file
具有read
和write
来自dir(tmp.file)
(因此,“文件类似于”?)
不过,这仍然会出错,并显示相同的错误消息
那么,我应该如何将标准文件重定向到临时文件呢?这样,它似乎可以工作:
with tempfile.NamedTemporaryFile(mode='w') as tmp:
with contextlib.redirect_stdout(tmp):
print('this')
注意:“模式”的默认值是“w+b”您缺少一个
的和在上下文库之前。重定向\u stdout(tmp)
。所以使用contextlib.redirect\u stdout(tmp):…