首页 > 解决方案 > Python 记录通过命令提示符的所有内容

问题描述

我正在尝试记录通过我的命令提示符的所有内容。这包括由 python 脚本启动的批处理脚本输出。

如果我像这样运行我的python文件

python logEverything.py >> logFile.txt

它给了我我想要的东西,而在命令提示符下打印的所有内容都将被放入该文件中。

问题在于它不再在命令提示符中显示任何内容。此外,我希望能够在程序内部指定日志文件路径。

那么有没有办法使用 Python记录通过命令提示符的所有内容?兼容windows和Linux?

所以 logEverything.py 会是这样的

import sys
def main():
    import io
    old_stdout = sys.stdout # Memorize the default stdout stream
    sys.stdout = buffer = io.StringIO()


    print('Log test')
    os.system('this is a test')
    print('More logging')


    #Finished -> put everything into log_file.txt
    sys.stdout = old_stdout
    whatWasPrinted = buffer.getvalue() 
    print(whatWasPrinted) # Why not to print it?
    buffer.close()

此解决方案部分有效,但未捕获 os.system() 的输出

标签: pythonlogging

解决方案


从askubuntu 上的这个问题:

command |& tee -a output.txt

标准输出和标准错误流都将被复制到文件中,同时在终端中仍然可见。如果文件已存在,则新数据将附加到文件末尾。

所以你可以使用python logEverything.py |& tee -a logFile.text


推荐阅读