简体   繁体   English

运行模块时如何使 __name__ == '__main__'

[英]How to make __name__ == '__main__' when running module

More specifically, I have a file更具体地说,我有一个文件

file file1.py:文件file1.py:

if __name__ == '__main__':
    a = 1

and from file file2.py, I want to do something like从文件file2.py,我想做类似的事情

import file1
print file1.a

without modifying file1.py无需修改 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.话虽如此,您应该真正考虑修改file1.py而不是使用此 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)您不再需要弄乱导入内部来做这样的事情(并且作为额外的好处,您将避免阻止访问您的真实__main__模块名称空间)

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.您需要在if __name__ == '__main__' scope 之外声明a Right now, it only exists within the scope of that if block.目前,它只存在于该if块的 scope 中。

a = 0
if __name__ == '__main__':
    a = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM