msg294645 - (view) |
Author: Stefan Seefeld (stefan) *  |
Date: 2017-05-28 13:28 |
The following code is supposed to catch and report errors encountered during the execution of a (python) script: ``` import traceback import sys try: env = {} with open('script') as f: exec(f.read(), env) except: type_, value_, tb = sys.exc_info() print (traceback.print_tb(tb)) ``` However, depending on the nature of the error, the traceback may contain the location of the error *within* the executed `script` file, or it may only report the above `exec(f.read(), env)` line. The attached tarball contains both the above as well as a 'script' that exhibit the problem. Is this a bug or am I missing something ? Are there ways to work around this, i.e. determine the correct (inner) location of the error ? (I'm observing this with both Python 2.7 and Python 3.5) |
|
|
msg294691 - (view) |
Author: Stefan Seefeld (stefan) *  |
Date: 2017-05-29 12:18 |
Some further experiements: Replacing the `exec(f.read(), env)` line by ``` code = compile(f.read(), 'script', 'exec') exec(code, env) ``` exhibits the same behaviour. If I remove the `try...except`, the correct (full) traceback is printed out. So it looks like the issue is with the traceback propagation through exception handlers when the error happens during parsing. |
|
|
msg294699 - (view) |
Author: Stefan Seefeld (stefan) *  |
Date: 2017-05-29 15:25 |
Answering my own question: It appears I can get the location of a syntax error by inspecting the raised `SyntaxError`, which solves my specific use-case. The bug remains, though: The traceback is incomplete if it stems from a syntax error. |
|
|
msg294707 - (view) |
Author: Serhiy Storchaka (serhiy.storchaka) *  |
Date: 2017-05-29 17:56 |
The traceback contain the location of the code that raised an exception when executed. In case of NameError this is a line in your script "x=u". In case of SyntaxError the code that failed is not in your script (it still is not executed), but in a compiler implicitly called by exec(). The line with exec() is correctly reported. The behavior looks correct to me. |
|
|
msg294709 - (view) |
Author: Stefan Seefeld (stefan) *  |
Date: 2017-05-29 18:46 |
OK, fair enough, that makes sense. As I said, in my last message, I was mainly simply trying to figure out the exact location of the error in the executed script, which I got from inspecting the SyntaxError. So if all of this is expected behaviour, I think we can close this issue. Many thanks for following up. |
|
|