Search code examples
pythonerror-handlingtraceback

Python - Traceback, how to show filename of imported


I've got the following:

try:
    package_info = __import__('app') #app.py
except:
    print traceback.extract_tb(sys.exc_info()[-1])
    print traceback.tb_lineno(sys.exc_info()[-1])

And what i get from this is:

[('test.py', 18, '<module>', 'package_info = __import__(\'app\')')]
18

Now this is almost what i want, this is where the actual error begins but i need to follow this through and get the actual infection, that is app.py containing an ä on row 17 not 18 for instance.

Here's my actual error message if untreated:

Non-ASCII character '\xc3' in file C:\app.py on line 17, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details", ('C:\app.py', 17, 0, None)), )

I've found some examples but all of them show the point of impact and not the actual cause to the problem, how to go about this (pref Python2 and Python3 cross-support but Python2 is more important in this scenario) to get the filename, row and cause of the problem in a similar manner to the tuple above?


Solution

  • Catch the specific exception and see what information it has. The message is formatted from the exception object's parameters so its a good bet that its there. In this case, SyntaxError includes a filename attribute.

    try:
        package_info = __import__('app') #app.py
    except SyntaxError, e:
        print traceback.extract_tb(sys.exc_info()[-1])
        print traceback.tb_lineno(sys.exc_info()[-1])
        print e.filename