Python不会读取sys.argv

use*_*028 7 python sys command-line-arguments

    import sys

    print sys.argv[1]
Run Code Online (Sandbox Code Playgroud)

这可能看起来非常基本,但我不能让Python从命令行读取任何内容.这就是上面的代码和我输入的内容:

    myfile.py helloworld
Run Code Online (Sandbox Code Playgroud)

我得到的回报是:

    IndexError: list index out of range
Run Code Online (Sandbox Code Playgroud)

它似乎对我有用,但不再适用,我尝试卸载并重新安装Python,但它仍然无法正常工作.

所以我的问题是,我做错了什么?还是我刚刚打破了Python?

谢谢你的帮助

使用:Windows 7 Python 2.7.2

Juu*_*nen 16

启动注册表编辑器(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/

  • 哇,这个注册表遗漏今天咬了我们,我们试图平衡Python 2.7 Anaconda和3.4安装并排.3.4安装程序省略了`%*`参数但我们需要为`HKEY_CLASSES_ROOT\Applications\pythonxx.exe\shell\open\command`键以及`HKEY_CLASSES_ROOT\py_auto_file\shell\open \命令设置它`关键 (2认同)

Obs*_*bot 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]
Run Code Online (Sandbox Code Playgroud)

收益:

$ ./foo.py 
you did not give any arguments

$ ./foo.py hello_world
hello_world
$ 
Run Code Online (Sandbox Code Playgroud)