在Windows上隐式调用Python脚本时sys.argv的内容

2 投票
1 回答
1298 浏览
提问于 2025-04-17 18:19

我在Windows 7上把 .PY 文件添加到了系统环境的 PATHEXT 变量中。同时,我也把 C:\scripts 加入了我的 PATH 变量。

假设我有一个非常简单的Python文件,路径是 C:\Scripts\helloscript.py。

print "hello"

现在我可以通过控制台来调用Python脚本,方法是:

C:\>helloscript

输出结果是:

hello

如果我把这个脚本改得更灵活一些,比如让它在控制台接收一个名字作为第二个参数,并打印出来和问候语一起:

import sys
print "hello,", sys.argv[1]

输出结果是:

c:\>helloscript brian
Traceback (most recent call last):
File "C:\Scripts\helloscript.py", line 2, in <module>
    print sys.argv[1]
IndexError: list index out of range

sys.argv 的内容看起来是:

['C:\\Scripts\\helloscript.py']

如果我像平常那样明确地调用这个脚本:

C:\>python C:\Scripts\helloscript.py brian

输出结果是:

hello, brian

如果我尝试使用 optparse,结果是类似的,虽然我可以避免出现错误:

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", "--firstname", action="store", type="string", dest="firstname")
(options, args) = parser.parse_args()
print "hello,", options.firstname

输出结果是:

hello, None

再次强调,如果我明确地调用这个脚本,它运行得很好。


这里有个问题。到底发生了什么?为什么在隐式调用我的脚本时,sys.argv 里只包含脚本名称,而没有其他内容呢?

1 个回答

4

结果我发现我需要手动编辑注册表:

HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command 的内容是:

"C:\Python27\python.exe" "%1"

而应该是:

"C:\Python27\python.exe" "%1" %*

撰写回答