如何检索导致异常的代码行(不是行号)?
这是一种尝试。
import sys, inspect
try:
1 / 0
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
code = str(inspect.getsourcelines(exc_tb.tb_frame.f_code))
print(code)
它返回脚本的第一行,而不是导致异常的行。
(['import sys, inspect\n'], 1)