作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 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/
我是一名优秀的程序员,十分优秀!