【问题标题】:sys.stdout.close() running foreversys.stdout.close() 永远运行
【发布时间】:2018-09-30 21:18:37
【问题描述】:

我想创建一个文件,其中包含来自我的 Python 脚本的所有日志消息。打印命令,每个单元需要运行多长时间等。 我使用以下内容:

import logging
sys.stdout = open('my/directory' +"log.txt", 'w')

print("here is my print message"+'\n')

sys.stdout.close()

我正在添加最后一个命令来检查我的脚本何时完成

print('finish!!!')

我在 Windows(我使用 spyder)和我使用的 Linux(Jyputer)中进行了测试 在这两种环境中,最后一个单元格都不会停止,我也从未收到“完成”消息。有任何想法吗?或者我需要做的任何替代方案? 我的问题是

【问题讨论】:

  • 你不应该篡改sys.stdout。您可以使用fout = open(.....,然后使用fout.write(... 而不是print(....,最后使用fout.close()。您永远不会收到您的消息,因为您关闭了应该收到它的文件。你的脚本确实完成了。
  • @CristiFati 好吧,OP 说他们正在 Jupyter 笔记本中运行代码,并且他们声称单元永远不会停止执行。不确定这是真的,但如果修补 sys.stdout 会导致 Jupyter 中出现一些奇怪的错误,我不会感到惊讶,它可能会做各种各样的事情,比如拦截 sys.stdout 以重定向它。
  • Chrissie:你为什么不直接使用logging 模块进行日志记录?另一种选择,使用file 参数print,所以print('hello', file=some_file_handler) 而不是弄乱 sys.stdout。
  • print 将使用 stdout 因此它永远不会打印(您关闭了文件)。您应该在最后复制标准输出并恢复。但是真的最好不要篡改(和其他cmets一样)
  • 嗨,克里斯蒂,感谢您的回答。只是一个澄清。我添加最后一个打印语句以查看 sys.stdout.close() 何时完成。我不希望在我的日志文件中看到此消息。

标签: python linux windows logging


【解决方案1】:

我遇到了同样的问题。假设你在 test.py 文件中有这个:

def print_hello():
    with open('log.txt') as f:
        sys.stdout = f
        print('hello')

如果你在命令行python test.py 中运行它,你不会有任何问题。但是如果你在 Jupyter notebook 中运行它,你必须像这样添加 stdout_obj:

stdout_obj = sys.stdout             # store original stdout 
print_hello()
sys.stdout = stdout_obj             # restore print commands to to interactive prompt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-19
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 2015-02-06
    • 2015-02-12
    相关资源
    最近更新 更多