gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:37:41 25 4
gpt4 key购买 nike

我在 Windows 7 上的系统环境 PATHEXT 变量中添加了 .PY 文件。我还添加了 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 不填充脚本名称以外的内容?

最佳答案

事实证明我必须手动编辑注册表:

HKEY_CLASSES_ROOT\Applications\python.exe\shell\open\command 为:

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

应该是:

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

关于python - 在 Windows 上隐式调用 Python 脚本时的 sys.argv 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15281951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com