【问题标题】:Python 3: Is there a way to get the line number of an error and the error statement when using exec [duplicate]Python 3:有没有办法在使用 exec 时获取错误的行号和错误语句 [重复]
【发布时间】:2015-08-27 19:35:53
【问题描述】:

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

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

【问题讨论】:

  • 您的意思是您想以编程方式知道行号?
  • @MartijnPieters 完全正确。
  • 附带问题:你为什么不使用import
  • @ReutSharabani 你到底是什么意思?
  • 你有一些 python 代码并且你正在使用exec 来执行它,为什么不使用import 来代替呢?

标签: python python-3.x


【解决方案1】:

你可以试试这个代码:

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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 2018-05-21
    相关资源
    最近更新 更多