0

Is there a way to get the line number of the error through executing a file? Let's say that I have the following code:

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

And the file has an error, in which IDLE pops up the following:

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'

I want to know the error statement (TypeError: unsupported operand type(s) for +: 'int' and 'str'), and the line number. This is not a duplicate because I am using Python 3, and not Python 2.

Henry Zhu
  • 2,488
  • 9
  • 43
  • 87

1 Answers1

1

You can try this code:

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))
avenet
  • 2,894
  • 1
  • 19
  • 26