Skip to main content
 首页 » 编程设计

python之为什么 (python -m ...) 导致 sys.argv 像 ['-c' , ...]

2025年05月04日13bluestorm

我有一个简单的脚本test.py

import sys 
print sys.argv 

如果我跑

python test.py abcd在cmd中,

我会得到 ['test.py', 'abcd'].

但是,如果我运行

python -m test.py abcd  

我会得到

['-c', 'abcd'] 
 
E:\Program Files (x86)\py\python.exe: No module named test.py.   

为什么 '-c' 在这里?我在 Stack Overflow 上搜索了有关 '-m' 的用法,但仍然感到困惑。

请您参考如下方法:

-m 开关告诉 python 寻找一个模块或包来导入并运行它的 __main__ 条目。查看-m switch documentation :

Search sys.path for the named module and execute its contents as the __main__ module.

对于您的情况,这意味着 Python 正在寻找一个名为 test.py 的包(注意:不是文件 用那个名字)。为了找到它,Python 首先导入模块 test(来自 test.py 文件),以查找名为 py 的子模块。这失败了。但在那个过程中,您的 test 模块仍在运行并打印出 sys.argv。

sys.argv 列表中的-c 开关是此过程如何工作的内部实现细节。参见 Python issue #8202一些细节:

As I recall, I used a bit of a hack to get main.c to implement -m correctly by piggybacking on the existing -c semantics. I'll find the hack and replace it with some proper '-c' or '-m' logic.

如果您想使用-m 开关,您需要删除.py 部分;那只是文件扩展名,而不是模块名称:

python -m test abcd