【问题标题】:Python: Revert sys.stdout to defaultPython:将 sys.stdout 恢复为默认值
【发布时间】:2018-07-14 14:18:46
【问题描述】:

我想将输出写入文件,因此我做到了

sys.stdout = open(outfile, 'w+')

但是我想在写入文件后打印回控制台

sys.stdout.close()
sys.stdout = None

我得到了

AttributeError: 'NoneType' object has no attribute 'write'

显然默认输出流不能是None那我对Python怎么说

sys.stdout = use_the_default_one()

【问题讨论】:

  • 一种方法是在分配给outfile之前将其存储为default_sysout,然后在关闭outfile后使用default_sysout将其分配回来,但以防万一我没有在哪里可以得到是吗?

标签: python python-3.x stdout


【解决方案1】:

在 Python3 中使用 redirect_stdout;以类似情况为例:

要将 help() 的输出发送到磁盘上的文件,请将输出重定向到 常规文件:

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)

【讨论】:

    【解决方案2】:

    您可以通过重新分配给sys.__stdout__ 来恢复到原始流。

    来自docs

    包含[s] 程序开始时 stdin、stderr 和 stdout 的原始值。它们在最终确定期间使用,并且无论 sys.std* 对象是否已被重定向,都可以用于打印到实际的标准流。

    redirect_stdout 上下文管理器可以用来代替手动重新分配:

    import contextlib
    
    with contextlib.redirect_stdout(myoutputfile):
        print(output) 
    

    (有一个类似的redirect_stderr

    更改sys.stdout 具有全局影响。例如,这在多线程环境中可能是不希望的。它也可能被认为是简单脚本中的过度工程。一种本地化的替代方法是通过 file 关键字参数将输出流传递给 print

    print(output, file=myoutputfile) 
    

    【讨论】:

    • sys.__stdout__:这正是我想要的。我的代码中少了一个变量 :) 耶!
    【解决方案3】:

    根据答案here,您不需要保存对旧标准输出的引用。只需使用 sys.__stdout__。

    另外,您可以考虑使用with open('filename.txt', 'w+') as f 并改用f.write

    【讨论】:

    • 谢谢,但我希望将所有警告和其他打印语句打印到文件中。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 2012-01-03
    • 1970-01-01
    • 2017-11-12
    相关资源
    最近更新 更多