我有一个Python小示例程序:
import sys
print ("This is the name of the script: "+ sys.argv[0])
print ("Number of arguments: " + str(len(sys.argv)))
print ("The arguments are: " + str(sys.argv))
我在 Windows CLI 中运行它:
python args.py -a -b
输出:
This is the name of the script: args.py
Number of arguments: 3
The arguments are: ['args.py', '-a', '-b']
看起来不错。现在我在不指定“python”的情况下调用它:
args.py -a -b
现在输出完全不同了:
This is the name of the script: C:\args.py
Number of arguments: 1
The arguments are: ['C:\\args.py']
我不应该得到同样的结果吗?尽管 python.exe 在这两种情况下都在执行程序,但为什么它显示不同的参数计数?
我该如何纠正这个问题?
看起来有一个解决方案在此 stackoverflow 线程,复制如下:
我在regedit关键字“python”中搜索,发现在
%*
之后缺少两个键"C:\Python27\python.exe" "%1":
Computer\HKEY_CLASSES_ROOT\Applications\python.exe
Computer\HKEY_CLASSES_ROOT\py_auto_file\shell\open\command
并且
与.py
相关,即使我尝试过py_auto_file
assoc .py Python.File
更改两个密钥解决了这个问题,谢谢!
不要使用 sys.arg 进行任何重要的参数解析。使用 argparse。