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

标签 python command-line

在 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/

相关文章:

command-line - 如果给定文件或目录被锁定(由任何进程使用),如何检查命令行?

node.js - Phonegap 3.4.0 无法构建新项目和更新旧项目

c 命令行参数

python - 如何使用图像处理库opencv和python语言提取 Material (2D工程图)的轮廓?

python - 将 python.exe 重命名为 python3.exe 以便与 Windows 上的 python2 共存

python - pd.read_csv 默认情况下将整数视为 float

mysql - 如何从命令行清除未执行的 MySQL 查询?

windows-7 - 将命令行日志重定向到文件时出现 `pause` 命令问题

Python:使列表生成器 JSON 可序列化

python - 如何在同一张图中使用 seaborn pointplot 和 violinplot? (更改点图的 xticks 和标记)