如何在 Python 中写出错误异常(以及实际错误)的错误行

How to write out line of error for error exception (as well as actual error) in Python

我是 运行 一个在 cron 作业上经常失败的脚本。它存在编码(UTF 等)问题,我正在尝试对其进行排序并解决问题。我这样做是为了让脚本在错误出现时将其写入 csv,这很好,但它没有告诉我错误发生在哪一行,所以我正在努力找出在哪里放入一些 .encode('utf-8') 来解决问题。谁能告诉我是否有办法添加到我的错误编写函数中来获取错误行?

我用来捕获错误的函数(也适用于其他代码)如下...

def error_output(error):
    t = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    new_data = [t, error]
    f = open('outputs/errors.csv', 'a')
    csv.writer(f, lineterminator='\n').writerows([new_data])
    f.close()

...脚本因此使用它:

if some condition:
    try:
        something
    except Exception as e:
        error_output(e)

...这很好地给我一个 CSV,它告诉我类似的事情:

2017-08-19 23:58:47 'ascii' codec can't encode character u'\u2019' in position 69: ordinal not in range(128)
2017-08-20 00:10:46 Failed to send request: 'utf8' codec can't decode byte 0xf0 in position 136: invalid continuation byte

...但我想要的不仅仅是错误的技术描述,我想知道代码中发生的位置,因为我已经在我的所有字符串中添加了.encode('utf-8') 它仍然像这样失败所以我需要知道错误的具体位置(就像我 运行 来自终端的脚本一样 - 我有时会这样做,但错误只会发生有时,可能是在处理奇怪的字符或表情符号等时)。

非常感谢任何帮助,因为这是一个令人沮丧的问题。谢谢!

您可以使用traceback

>>> import traceback
>>> 
>>> def f():
...     if True:
...         1 / 0
... 
>>> try:
...     f()
... except:
...     print(traceback.format_exc())
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 3, in f
ZeroDivisionError: integer division or modulo by zero

你真的应该使用 logging 并添加到格式化程序 - %(lineno)d

类似于:

import logging
logging.basicConfig(format='%(asctime)s - %(lineno)d %(message)s', level=logging.DEBUG)
logging.debug('This message should appear on the console')
logging.info('So should this')
logging.warning('And this, too')

如果您需要在文件中阅读 FileHandler。这个技巧以后也会让你受益。