The code given to exec
below will pass without compile errors, but will result in an run-time error at "error" statement:
globs = {}
exec('''
def main():
print('Hello Python')
error # Makes run-time error
''', globs)
globs['main']()
The error message is:
Traceback (most recent call last): File "C:\work\sandbox.py", line 11, in globs['main']() File "<string>", line 4, in main NameError: name 'error' is not defined
The location information of only File "<string>", line 4, in main
is not very useful, for example when trying the locate the origin of the code which can be from a file.
Note that the above is a simplified example to show the issue. In the actual program the code defines several functions that are executed at different locations in the main program.
Is there some way to provide the code from exec
with another location than "<string>", so this other location is shown if an exception occurs in the exec code?
You can first compile
your code and give it a filename argument:
code = compile('error', 'foo.py', 'exec')
exec(code)
Output:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "foo.py", line 1, in <module>
NameError: name 'error' is not defined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With