系统工作,但是系统标准输出是吗

2024-09-22 20:19:30 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个名为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不起作用。在


Tags: 文件函数sourcetargetosstdoutsys重定向
1条回答
网友
1楼 · 发布于 2024-09-22 20:19:30

正如格雷格在评论中提到的那样,这行不通。我通常做的是暂时改变我的标准。在

@contextmanager
def replace_stdout(replacement):
    _stdout = sys.stdout
    sys.stdout = replacement
    try:
        yield
    finally:
        sys.stdout = _stdout

并将该上下文管理器用于:

^{pr2}$

这种用法不关心初始stdout是否有FD。在

相关问题 更多 >