Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 16773

How to set the value of __file__ in an exec() body of code?

$
0
0

I'm using this python3 construct to exec a PY file that I read in.When the read file throws an exception, the reported location is wrong.Example:

   # create Globals Dict   fn='foobar.py'   g={ '__file__' : fn }   l={ '__file__' : fn }   text = open(fn).read()   # goal, pass globals and locals to the exec here.   exec( text, g, l )

where 'foobar.py' contains:

print("FILE: %s" % __file__ )raise Exception('Bang!')

The output for print("File: %s" % __file__ ) is correct

For the exception, it is wrong, I get this:

   File "<string>", line 2 in <module>Exception: Bang!

That is not what I am expecting, I purposely want to set the FILENAME where the exception occurred to the name of the file that I read in, in this case: 'foobar.py'


Viewing all articles
Browse latest Browse all 16773

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>