我做了:foo/
__init__.py
__main__.py
两个文件是:import __main__
print('in init')
print('init name',__name__)
以及print('main name',__name__)
print('in main')
if __name__=='__main__':
print('in main main block')
如果我直接运行__main__:1538:~/mypy$ python foo/__main__.py
('main name', '__main__')
in main
in main main block
如果我调用目录,它也会执行同样的操作。它不导入__init__.py。1541:~/mypy$ python foo
('main name', '__main__')
in main
in main main block
但是从一个shell中,它同时加载两个文件1542:~/mypy$ python
....
>>> import foo
('main name', 'foo.__main__')
in main
in init
('init name', 'foo')
但它没有使用__main__的if __name__块-名称不对,现在是foo.__main__。
相关文件Execute the Python code contained in script, which must be a filesystem path (absolute or relative) referring to either a Python file, a directory containing a __main__.py file, or a zipfile containing a __main__.py file.This module represents the (otherwise anonymous) scope in which the interpreter’s main program executes — commands read either from standard input, from a script file, or from an interactive prompt. It is this environment in which the idiomatic “conditional script” stanza causes a script to run:
我用__init__.py创建了另一个目录,但没有主目录:1558:~/mypy$ python foo1
/usr/bin/python: can't find '__main__' module in 'foo1'
1558:~/mypy$ python
...
>>> import foo1
('in init', 'foo1')
>>>
import可以,但我不能run目录。