How To Make __name__ == '__main__' When Running Module
More specifically, I have a file file file1.py: if __name__ == '__main__': a = 1 and from file file2.py, I want to do something like import file1 print file1.a without modify
Solution 1:
importimpm= 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.
Solution 2:
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)
Solution 3:
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.
Solution 4:
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
Post a Comment for "How To Make __name__ == '__main__' When Running Module"