Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

For me

except Exception as e:
    print e.__unicode__()

works with returning exactly same message

To be python 2.5 and 3.x compatible at the same time (2.5 does not support except Exception as e), use

try:
    package_info = __import__('app') #app.py

except SyntaxError:
    exc_type, exc, tb = sys.exc_info()
    print(exc)
    print('\n\n'.join(traceback.format_tb(tb, limit=5)))

prints

Non-ASCII character '\xc3' in file /foo/app.py on line 2, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details (app.py, line 2)
  File "foo.py", line 6, in <module>
    package_info = __import__('app') #app.py
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top