m开关的用途是什么?

2024-05-17 23:01:05 发布

您现在位置:Python中文网/ 问答频道 /正文

你能给我解释一下打电话的区别吗

python -m mymod1 mymod2.py args

以及

python mymod1.py mymod2.py args

在这两种情况下,似乎都调用了mymod1.py,并且sys.argv

['mymod1.py', 'mymod2.py', 'args']

那么-m开关的作用是什么?


Tags: pysys情况args区别argvmymod1mymod2
2条回答

PEP 338Rationale部分的第一行显示:

Python 2.4 adds the command line switch -m to allow modules to be located using the Python module namespace for execution as scripts. The motivating examples were standard library modules such as pdb and profile, and the Python 2.4 implementation is fine for this limited purpose.

所以您可以用这种方式在Python的搜索路径中指定任何模块,而不仅仅是当前目录中的文件。你说的对,python mymod1.py mymod2.py args有完全相同的效果。Scope of this proposal部分的第一行声明:

In Python 2.4, a module located using -m is executed just as if its filename had been provided on the command line.

有了-m更多的功能是可能的,比如处理作为包的一部分的模块,等等。这就是PEP 338的其余部分。更多信息请阅读。

还有一件事我认为值得一提

python -m some_package some_arguments

python解释程序将在包路径中查找要执行的__main__.py文件。相当于:

python path_to_package/__main__.py somearguments

它将在以下时间后执行内容:

if __name__ == "__main__":

如果文件不存在,则无法直接执行此包。

相关问题 更多 >