0

我正在寻找一些帮助,以确保所有错误都保存到文本文件中,但似乎无法找到一种方法来确保所有错误都进入文件而不定义异常处理应该查看的部分。

我浏览了http://docs.python.org/2/tutorial/errors.html但找不到任何适合我需要的东西:/

我确信必须有一个简单的方法来做到这一点。提前致谢 - Hyflex

4

2 回答 2

4
import sys
sys.stderr = open("some_log.txt","wb")

我认为至少...

>>> import StringIO
>>> import sys
>>> s = StringIO.StringIO()
>>> sys.stderr = s
>>> 5=7
>>> 5/0
>>> s.seek(0)
>>> s.read()
'  File "<stdin>", line 1\nSyntaxError: can\'t assign to literal\nTraceback (mos
t recent call last):\n  File "<stdin>", line 1, in <module>\nZeroDivisionError:
integer division or modulo by zero\n'
于 2013-06-21T23:31:36.967 回答
1

您可以将整个程序嵌入到一个基础中Exception

try:
    main()                          # Entry point of your program
except Exception as e:
    str_e = "Error({0}): {1}".format(e.errno, e.strerror)
    # Print "str_e" to file
    with open("errlog.txt", "a") as myfile:
        myfile.write(str_e)
于 2013-06-21T23:35:40.313 回答