Python无法读取sys.argv
import sys
print sys.argv[1]
嗨,
这看起来可能很基础,但我就是无法让Python从命令行读取任何东西。
这是我上面的代码,我输入的是:
myfile.py helloworld
然后我得到的是:
IndexError: list index out of range
我觉得之前有一次是可以的,但现在不行了。我尝试过卸载再重新安装Python,但还是不行。
所以我的问题是,我是不是做错了什么?还是我把Python搞坏了?
谢谢你的帮助
使用的系统:
Windows 7
Python 2.7.2
2 个回答
23
首先,打开注册表编辑器(regedit)。然后,把 HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command 这个键的值设置为:
"C:\Python26\python26.exe" "%1" %*
这个解决方案的来源是: http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/
5
你确定你是按照你想的方式来运行你的Python脚本吗?
#!/usr/bin/python
import sys
if len(sys.argv) < 2:
print "you did not give any arguments\n"
else:
print sys.argv[1]
返回结果是:
$ ./foo.py
you did not give any arguments
$ ./foo.py hello_world
hello_world
$