将'print()'和'os.system'都重定向到日志文件,同时在控制台中保留原始输出

时间:2019-01-05 05:28:27

标签: python python-3.x windows

我一直在阅读有关redirect prints to log file的信息,但是我不明白为什么接受的答案不能真正按预期工作。

原始代码在Python2中,我在使用Python3时对它进行了一些修改。

接受的答案https://stackoverflow.com/a/2513511/9013730

import os

def test():
    cmd = 'ver'
    print("1. Running command:",cmd)    # message.log only, NOT in console
    os.system(cmd)                      # This appear in console only, but not in message.log
    print('3. Done')                    # message.log only, NOT in console

import sys
old_stdout = sys.stdout
log_file = open("message.log","w")
sys.stdout = log_file
print("This will be written to message.log")    # message.log only, NOT in console
test()
sys.stdout = old_stdout
log_file.close()

控制台输出

如您所见,在控制台中仅打印出os.system(cmd),而在message.log输出中却没有看到它。

Microsoft Windows

message.log输出

当我检查message.log输出时,os.system(cmd)不在那儿。

This will be written to message.log
1. Running command: ver
3. Done

是否可以在控制台和message.log中产生相似的(精确)输出?

控制台和message.log中所需的输出

This will be written to message.log
1. Running command: ver
Microsoft Windows
3. Done

0 个答案:

没有答案
相关问题