sys.stdout.close()永远运行

时间:2018-04-20 07:59:20

标签: python linux windows logging

我想创建一个包含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) 在这两种环境中,最后一个单元格永远不会停止,而且我永远不会完成“最后一个单元格”。信息。有任何想法吗?或者我需要做什么选择? 我的问题是

1 个答案:

答案 0 :(得分:0)

我有同样的问题。假设您在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
相关问题