`python file.py` 和 `python -m file` 的区别

Difference between `python file.py` and `python -m file`

在python3中:

令我惊讶的是,我在这些问题上发现的信息如此之少。也许我没有使用正确的术语进行搜索?提前致谢!

python -m ...

用于运行ning python库模块,如pip,IPython等

python file.py

但是用于 运行 带有 python 解释器的文件。

What is the difference between calling python path/to/file.py and python -m path.to.file ?

Python -m module_name 是调用特定模块的快捷方式。通常这是一个已安装的包,里面有一个 __main__.py 模块。 (例如 python -m pip 调用 pip/__main__.py

所以python -m pip等同于python path/to/my/python/lib/site-packages/pip/__main__.py

How does it affect the working directory ? ( os.getcwd() )

没有

Does it have a link with the presence / absence of an init.py file located in path/to ?

首先:可能有一些混淆值得澄清:python -m 没有将路径作为参数。它需要一个模块的 name 来执行。

所以,简短的回答:没有。

长答案:模块如何按名称执行 python -m 取决于它是否是一个包。 __init__.py 的存在可以表示该目录是包的名称,就像 pip 一样,因此它会在包内寻找 __main__