gpt4 book ai didi

python - -m 标志在 Python 2 和 3 之间有何不同?

转载 作者:太空宇宙 更新时间:2023-11-03 13:38:04 25 4
gpt4 key购买 nike

在 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 toiterate over each directory in the parent path as it does in Python3.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 importedand returned.

  • If not, but /foo.{py,pyc,so,pyd} is found, amodule is imported and returned. The exact list of extension varies byplatform and whether the -O flag is specified. The list here isrepresentative.

  • If not, but /foo is found and is adirectory, it is recorded and the scan continues with the nextdirectory 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com