在 Python 3 中,我可以在命令行中使用 -m 标志将任何目录作为 Python 包运行,或者在这些目录中运行带有相对导入的 python 模块。然而,在 Python 2 中情况似乎并非如此。
假设我有以下文件结构:
C:\mflag
└───pack
hey.py
hey.py 的内容是:
from __future__ import print_function
print("Hello!")
为什么这两个命令的行为不同?
C:\mflag>python -m pack.hey
Hello!
C:\mflag>python2 -m pack.hey
C:\Python27\python2.exe: No module named pack
最佳答案
这是一个命名空间包,由 PEP 0420 引入;具体来说:
During import processing, the import machinery will continue to iterate over each directory in the parent path as it does in Python 3.2. While looking for a module or package named "foo", for each directory in the parent path:
If /foo/_ _ init _ _.py is found, a regular package is imported and returned.
If not, but /foo.{py,pyc,so,pyd} is found, a module is imported and returned. The exact list of extension varies by platform and whether the -O flag is specified. The list here is representative.
If not, but /foo is found and is a directory, it is recorded and the scan continues with the next directory in the parent path.
Otherwise the scan continues with the next directory in the parent path.
关于python - -m 标志在 Python 2 和 3 之间有何不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36502214/