首页 > 解决方案 > 如何知道 Python 中哪个函数引发了异常

问题描述

我有一个超过 2000 行的 python 脚本,它通过生产服务器上的以下异常,我无法在本地重现问题来调试它,我不知道它来自哪里。

Exception TypeError: TypeError("argument of type 'NoneType' is not iterable",) in <bound method Popen3.__del__ of <popen2.Popen3 instance at 0x7fccba7b65f0>> ignored
Exception TypeError: TypeError("argument of type 'NoneType' is not iterable",) in <bound method Popen3.__del__ of <popen2.Popen3 instance at 0x7fccba7b62d8>> ignored
Exception TypeError: TypeError("argument of type 'NoneType' is not iterable",) in <bound method Popen3.__del__ of <popen2.Popen3 instance at 0x7fccba824ef0>> ignored
Exception TypeError: TypeError("argument of type 'NoneType' is not iterable",) in <bound method Popen3.__del__ of <popen2.Popen3 instance at 0x7fccba824f80>> ignored

有没有办法让解释器像 Java 一样打印异常的跟踪?能够知道是什么引发了这个异常。

标签: pythondebugging

解决方案


最简单的方法是traceback.print_exc()except块中使用:

try:
    1[0]  # raises
except TypeError:
    traceback.print_exc()
    raise

推荐阅读