scope - Python exec and __name__ -


when run:

exec "print __name__" 

it prints __main__.

but when run:

exec "print __name__" in {} 

it prints __builtin__.

how make second example print __main__?

what try achieve run piece of code exec perspective of looks run command line.

i tun code clean scope second example breaks code relying on if __name__ == "__main__". how fix this?

you use imp.load_module instead:

import imp  open(mainfile) src:     imp.load_module('__main__', src, mainfile, (".py", "r", imp.py_source)) 

this imports file __main__ module, executing it.

note takes actual file object when type set imp.py_source, you'd need create temporary file work if source code comes somewhere other file.

otherwise, can set __name__ manually:

>>> src = '''\ ... if __name__ == '__main__': print 'main!' ... else: print 'damn', __name__ ... ''' >>> exec src main! >>> exec src in {} damn __builtin__ >>> exec src in {'__name__':'__main__'} main! 

Comments

  1. Really explains everything in detail, the article is very interesting and effective.Otherwise any one who want to learn python core to advance contact us on 9311002620 or visit :-https://www.htsindia.com/Courses/python/python-training-institute-in-south-delhi

    ReplyDelete

Post a Comment

Popular posts from this blog

shader - OpenGL Shadow Map -

stringtemplate - StringTemplate4 if conditional with length -