Python sys.stdout.close()将永远运行

Python sys.stdout.close()将永远运行,python,linux,windows,logging,Python,Linux,Windows,Logging,我想创建一个包含Python脚本中所有日志消息的文件。打印命令,每个单元格运行ect所需的时间。 我使用以下方法: import logging sys.stdout = open('my/directory' +"log.txt", 'w') print("here is my print message"+'\n') sys.stdout.close() 我正在添加最后一个命令,以检查脚本何时完成 print('finish!!!') 我在Windows(使用spyder)和Linu

我想创建一个包含Python脚本中所有日志消息的文件。打印命令,每个单元格运行ect所需的时间。 我使用以下方法:

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)中进行了测试 在这两种环境中,最后一个单元格从未停止,我也从未收到“完成”消息。有什么想法吗?或者我需要做什么?
我的问题是我也有同样的问题。假设您在test.py文件中有以下内容:

def print_hello():
    with open('log.txt') as f:
        sys.stdout = f
        print('hello')
如果在命令行
python test.py
中运行此命令,则不会有任何问题。但如果在Jupyter笔记本中运行此功能,则必须添加stdout_obj,如下所示:

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

您不应该篡改
sys.stdout
。您可以使用
fout=open(……
),然后使用
fout.write(…
而不是
print(…
),最后使用
fout.close()
。你永远不会收到你的消息,因为你关闭了应该收到它的文件。而且你的脚本也完成了。@CristiFati好吧,OP说他们正在Jupyter笔记本上运行代码,他们声称该单元格从未停止执行。我不确定这是真的,但如果修补
sys.stdout
我不会感到惊讶Jupyter中可能会出现一些奇怪的错误,它可能会执行各种操作,比如拦截
sys.stdout
来重定向它。克丽丝:为什么不使用
logging
模块来做日志记录呢?另一种选择是,使用
file
参数来
print
,所以
print('hello',file=some\u file\u处理程序)
不要弄乱sys.stdout。
print
将使用
stdout
,因此它永远不会打印(您关闭了文件)。您应该复制stdout并在最后还原。但最好不要篡改它(与其他注释一样)嗨,克里斯蒂,谢谢你的回答。只需要一个澄清。我添加了最后一个打印语句,以便查看sys.stdout.close()何时完成。我不希望在我的日志文件中看到此消息。