我知道:将stdout重定向到Python中的文件?
我在问如何进行以下操作:
In [2]: with tempfile.NamedTemporaryFile() as tmp:
...: contextlib.redirect_stdout(tmp):
...: print('this')
哪些错误:
TypeError: a bytes-like object is required, not 'str'
从文档(https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout):
上下文管理器,用于将sys.stdout临时重定向到另一个文件或类似文件的对象。
搜索哪个给了我这篇文章:Python中的类文件对象到底是什么?状态:
将面向文件的API(使用read((或write((等方法(公开给底层资源的对象
这让我认为以下方法可能会奏效:
In [2]: with tempfile.NamedTemporaryFile() as tmp:
...: contextlib.redirect_stdout(tmp.file):
...: print('this')
因为tmp.file
具有来自dir(tmp.file)
的read
和write
(所以是"文件样"?(。
不过,这仍然会出错,并显示相同的错误消息。
那么,我应该如何将标准重定向到临时文件呢?
这样,它似乎可以工作:
with tempfile.NamedTemporaryFile(mode='w') as tmp:
with contextlib.redirect_stdout(tmp):
print('this')
注意:"模式"的默认值为"w+b">