Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give exec code meaningful location to show if exception?

Tags:

python

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?

like image 374
EquipDev Avatar asked Mar 04 '15 13:03

EquipDev


1 Answers

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
like image 109
André Laszlo Avatar answered Oct 16 '22 14:10

André Laszlo