有一个名为redirect的函数,它将文件source
上的操作临时重定向到文件target
。在
def redirect(source, target):
source.flush()
fd = source.fileno()
with os.fdopen(os.dup(fd), source.mode) as source2:
os.dup2(target.fileno(), fd)
try:
yield
finally:
source.flush()
os.dup2(source2.fileno(), fd)
它是从同一模块调用的
^{pr2}$在编译时,它用于生成AttributeError
AttributeError: StringIO instance has no attribute 'fileno'
在fd = source.fileno()
行。在
但是当我将sys.stdout
替换为sys.__stdout__
时,没有这样的错误,测试成功通过了。在
现在我真的很困惑,为什么__stdout__
起作用而stdout
不起作用。在
正如格雷格在评论中提到的那样,这行不通。我通常做的是暂时改变我的标准。在
并将该上下文管理器用于:
^{pr2}$这种用法不关心初始stdout是否有FD。在
相关问题 更多 >
编程相关推荐