Capture Console info to python in file

问题描述 投票:1回答:2

我想将在控制台中捕获的所有信息捕获到一个文件中。而不仅仅是控制台print()函数。堆栈上有关于如何将print()重定向到文件的代码,但如果发生错误,则不会。就像您的程序会出现以下错误一样。它会给一个

indexError: List index out of rang 

我想将所有控制台信息捕获到一个文件中,而无需在各处编写try和exception。

我的总体任务是使用pyInstaller创建一个带有日志文件的程序,并在日志中捕获控制台以了解该程序在哪里中断。

list= ["hello","Bey"]
counter=0
while counter < 100:
    print(list[counter])
    counter=counter+1

#What the console print out. 
#print(list[counter])
#IndexError: list index out of range
python stdout
2个回答
0
投票

您可能应该将日志记录模块用于此任务。但是,仍然希望将所有控制台输出重定向到文件,则可以将stdout和stderr的文件描述符都重定向到2个不同的文件。因此,调用python脚本的控制台命令将类似于

python myscript.py 1>C:\Python27\out_log.log 2>C:\Python27\err_log.log

执行后,out_log.log将具有“ hello”和“ Bey”,而异常将被重定向到err_log.log文件。在这种情况下,控制台上将不会打印任何内容。


0
投票

pip安装日志记录是您的朋友https://docs.python.org/2.6/library/logging.html

© www.soinside.com 2019 - 2024. All rights reserved.