如果我不知道错误在哪里,如何将Python错误打印到txt文件中

9ceoxa92  于 4个月前  发布在  Python
关注(0)|答案(5)|浏览(86)

我有一个非常大的Python 3.x程序在Windows中运行。它在99.9%的时间内都运行得很好,但偶尔会崩溃。我不确定是什么原因导致崩溃,可能是很多事情。由于我必须运行程序“compiled”.exe,出于安全原因,使用不可见的控制台(不要问),我不会看到任何形式的控制台读出时,它死了。所以很明显,这将是伟大的,如果我能让它输出崩溃追溯作为一个文本文件,而不是。
我对Python中的try/except很熟悉,但导致问题的代码可能在任何地方,我不想在数千行代码中的每一行都写一个单独的try/except。有没有一种方法可以让程序总是以文本文件的形式输出任何程序停止错误,不管是哪一行代码导致了问题,或者可能的错误是什么

fwzugrvs

fwzugrvs1#

有时你不能在终端中使用try/except或>。
你可以使用sys excepthook.把这个添加到开头:

import sys
import traceback

def excepthook(exctype, value, tb):
    with open("mylog.txt", "w") as mylog:
        traceback.print_exception(exctype, value, tb, file=mylog)

sys.excepthook = excepthook
##########
# your code

字符串
在那之后,所有的追溯将被打印到mylog.txt。

vlju58qv

vlju58qv2#

我最终编写了自己的日志函数

# Takes two inputs - logfile (path to desired .csv), and data to be written
# Writes "Y-M-D|H:M:S, data\n"
    f = open(logfile, 'a+')
    currentdate = time.strftime('%Y-%m-%d|%H:%M:%S')
    f.write(currentdate + ',' + data +'\n')
    f.close()

字符串
它需要timedatetime,我不确定是哪一个。另外,你需要确保日志文件存在。
然后我会把它放在我需要的任何地方,例如:logger(ERRLOG, "OCR didn't find poop. Check {}".format(ocr_outfilepath))

pw136qt2

pw136qt23#

我不确定这是什么类型的程序,也不知道你是如何运行它的,但是你可以试着运行你的Python程序,并将它的所有输出(或所有错误)重定向到一个文件。
例如,如果我有一个非常做作的Python脚本示例,如下所示

def do_stuff():
    s = [1, 2, 3, 4, 5]
    print(s[6])

if __name__ == "__main__":
    do_stuff()

字符串
这是故意引发IndexError异常的。
您可以这样运行它:

$ python test.py &> mylogs.txt

$ cat mylogs.txt 
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    do_stuff()
  File "test.py", line 4, in do_stuff
    print(s[6])
IndexError: list index out of range


它将所有输出和错误重定向到一个文件。
或者,如果您可以将其显示在控制台上 *,并 * 将其重定向到文件:

$ python test.py 2>&1 | tee mylogs.txt
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    do_stuff()
  File "test.py", line 4, in do_stuff
    print(s[6])
IndexError: list index out of range

$ cat mylogs.txt 
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    do_stuff()
  File "test.py", line 4, in do_stuff
    print(s[6])
IndexError: list index out of range


这样,您就不需要修改代码中的任何内容。
请注意,此解决方案适用于Linux或Mac系统。
请参阅other StackOverflow posts for redirecting Python output to a file

owfi6suc

owfi6suc4#

这将把所有错误从控制台记录到一个txt文件中。每次运行脚本时,它都会清除以前的错误并从头开始。如果你想保存以前的错误,请将“w”改为“a”。将“w”放在代码的开头:

import sys

with open('./errors.txt', 'w') as file5:  
    file5.write('')
    file5.close()

sys.stderr = open("./errors.txt", "a")

字符串

uoifb46i

uoifb46i5#

在你的代码中,你必须有一个可能崩溃的代码的单一入口点(至少在主脚本中)。你可以将其 Package 在try/except对中,然后使用traceback模块中的函数在发生异常时将异常打印到文件中:
变更:

if __name__ == "__main__":
    do_stuff()

字符串
收件人:

import traceback

if __name__ == "__main__":
    try:
        do_stuff()
    except:
        with open("exceptions.log", "a") as logfile:
            traceback.print_exc(file=logfile)
        raise


如果你愿意的话,你可以添加一些额外的代码来向文件中写入额外的输出,带有时间/日期戳或任何其他你认为可能有用的信息。如果你想对代码的某些部分进行给予特殊的审查,你可能需要添加额外的try/except块,或多或少与上面的类似。例如,你可以将一个块放入一个循环中,在这里,如果发生异常,可以打印出循环值:

for x in some_iterable:
    try:
        do_something_with(x)
    except:
        with open("exceptions.log", "a") as logfile:
            print("Got an exception while handling {!r} in the loop:".format(x)
            traceback.print_exc(file=logfile)
        raise   # you could omit this line to suppress the exception and keep going in the loop


如果你想要一个更可配置的系统来处理文件写入问题,你也可以使用logging模块。logging.debuglogging.exception函数都读取traceback模块使用的相同异常信息,但是有了更多的选项来自己格式化东西,注意,设置日志记录比手动打开一个文件要复杂一些。

相关问题