Python will not read sys.argv

ⅰ亾dé卋堺 提交于 2019-12-08 19:18:45

问题


    import sys

    print sys.argv[1]

hi,

this may seem very basic but I can't get Python to read in anything from the command line. thats the code above and what I type is:

    myfile.py helloworld

and what i get back is:

    IndexError: list index out of range

It seemed to work once for me but won't work any more, and I've tried uninstalling and reinstalling Python and it still doesnt work.

So my question is, am I doing anything wrong? or have I just broken Python?

Thanks for any help

Using: Windows 7 Python 2.7.2


回答1:


Are you sure you are calling your python script the way you think you are?

#!/usr/bin/python
import sys

if len(sys.argv) < 2:
    print "you did not give any arguments\n"
else:
    print sys.argv[1]

returns:

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

$ ./foo.py hello_world
hello_world
$ 



回答2:


Start the registry editor (regedit). Set the HKEY_CLASSES_ROOT\Applications\python26.exe\shell\open\command key to: "C:\Python26\python26.exe" "%1" %*

Source of this solution: http://eli.thegreenplace.net/2010/12/14/problem-passing-arguments-to-python-scripts-on-windows/



来源:https://stackoverflow.com/questions/7969168/python-will-not-read-sys-argv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!