Python exec and __name__

When I run:

exec "print __name__"

he is typing __main__.

But when I run:

exec "print __name__" in {}

he is typing __builtin__.

How to make a second example also for printing __main__?

What I'm trying to achieve is to run a piece of code with exec, so that in future it looks like it was being launched from the command line.

I would like to configure the code with a clean scope, but the second example breaks the code into if __name__ == "__main__". How to fix it?

+5
source share
2 answers

Instead, imp.load_moduleyou can use

import imp

with open(mainfile) as src:
    imp.load_module('__main__', src, mainfile, (".py", "r", imp.PY_SOURCE))

This imports the file as a module __main__, executing it.

, -, imp.PY_SOURCE, , , -, .

__name__ :

>>> src = '''\
... if __name__ == '__main__': print 'Main!'
... else: print 'Damn', __name__
... '''
>>> exec src
Main!
>>> exec src in {}
Damn __builtin__
>>> exec src in {'__name__':'__main__'}
Main!
+4

, __name__ exec:

exec "print __name__" in {'__name__': '__main__'}
0

All Articles