How to make __name__ == '__main__' when running module
More specifically, I have a file
file file1.py:
if __name__ == '__main__':
a = 1
开发者_Python百科
and from file file2.py, I want to do something like
import file1
print file1.a
without modifying file1.py
import imp
m = imp.find_module('file1')
file1 = imp.load_module('__main__', *m)
That being said, you should really think about modifying file1.py
instead of using this hack.
from runpy import run_module
data = run_module("file1", run_name="__main__")
print data["a"]
You don't need to mess with the import internals to do things like this any more (and as an added bonus, you will avoid blocking access to your real __main__
module namespace)
You can't; that's the purpose of the main sentinel in the first place. If variables defined in the main sentinel are useful outside of it then they should be defined outside of it to begin with.
You would need to declare a
outside of the if __name__ == '__main__'
scope. Right now, it only exists within the scope of that if
block.
a = 0
if __name__ == '__main__':
a = 1
精彩评论