Python 3:有没有办法在使用exec时获取错误的行号和错误语句

时间:2015-08-27 19:35:53

标签: python python-3.x

有没有办法通过执行文件来获取错误的行号?我们说我有以下代码:

exec(open("test.py").read())

该文件有错误,IDLE弹出以下内容:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1487, in __call__
    return self.func(*args)
  File "C:\Users\henrydavidzhu\Desktop\Arshi\arshi.py", line 349, in runFile
    exec(open(self.fileName).read())
  File "<string>", line 2, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我想知道错误陈述(TypeError: unsupported operand type(s) for +: 'int' and 'str')和行号。这不是重复,因为我使用的是Python 3,而不是Python 2

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

import sys
import traceback

try:
    exec(open('test.py').read())
except Exception as e:
    exc_type, ex, tb = sys.exc_info()
    imported_tb_info = traceback.extract_tb(tb)[-1]
    line_number = imported_tb_info[1]
    print_format = '{}: Exception in line: {}, message: {}'
    print(print_format.format(exc_type.__name__, line_number, ex))