将一个文件命名为'__main__.py', 然后在其他文件import它,那么它的'__name__'会是什么?

python 版本2.7.2

__main__.py 文件内容如下

print '__name__ is ' + __name__

test_import.py 文件内容如下

import __main__

cmd 执行 python test_import.py

输出空空如也 求解


好吧,这是一个很小白的问题.

http://docs.python.org/2/library/main.html
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:

if __name__ == "__main__":
    main()
阅读 5.4k
2 个回答

你看看你 import 进来的那个 __main__ 是什么 =w=

test_import.py 作为脚本执行时,自身的 __name__ 就是 '__main__',在 sys.modules 中,'__main__' 模块就是 test_import.py 自己。

导入 __main__ 时,Python首先在 sys.modules 中查找以 '__main__' 为名的模块,结果就是找到了自己,而自己已经存在于 sys.modules 中,所以,不会有任何输出。

导入后,你可以直接使用 __main__ 引用主模块,而无需使用 sys.modules['__main__']。

__main__.py 用于模块包需要作为命令行使用时,例如 python -m pkg,此时将先执行 __main__.py 后执行 __init__.py。

__main__.py 文件应用请参考 [1]: https://blog.zengrong.net/pos...

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题