变量__spec__
来自哪里?
$ brew install python3
$ python3
Python 3.4.2 (default, Jan 5 2015, 11:57:21)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.56)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
# Under Python 2.7.x this gives a NameError
>>> None is __spec__
True
答案 0 :(得分:6)
来自the Python Language Reference, Part 5: The Import System(强调我的):
__spec__
属性必须设置为导入模块时使用的模块规范。这主要用于内省和重新加载。设置__spec__
适用于modules initialized during interpreter startup。 一个例外是__main__
,其中__spec__
在某些情况下设置为无。版本3.4中的新功能。
答案 1 :(得分:2)
根据Python 3 docs,如果您使用交互式promt,__spec__
始终为None
:
使用-m选项启动Python时,
__spec__
设置为 相应模块或包的模块规格。__spec__
也是 在__main__
模块作为执行a的一部分加载时填充 目录,zipfile或其他sys.path条目。在其余情况下,
__main__.__spec__
设置为无,作为代码 用于填充__main__
并不直接对应于 可导入的模块:
- 互动提示
- -c switch
- 从stdin
运行- 直接从源或字节码文件运行