7
    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

user1024028
  • 73
  • 1
  • 1
  • 3
  • What happens when you just `print sys.argv`? And does it work, when calling the file via `python.exe myfile.py helloworld`? – poke Nov 01 '11 at 16:07
  • ah, thanks for your responces, managed to get it working. had a very silly mistake, didnt add python to the Path in system variables – user1024028 Nov 01 '11 at 16:16
  • For those having trouble passing arguments to a script in Windows without prepending it with a call to Python (e.g. `python foo.py a` works but `foo.py a` doesn't,) scroll past the first answer. – eenblam Jun 16 '16 at 14:56

2 Answers2

21

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/

Juuso Ohtonen
  • 8,826
  • 9
  • 65
  • 98
  • 4
    wow, this registry omission bit us today, we were trying to balance a Python 2.7 Anaconda and 3.4 installation side by side. The 3.4 installer omitted that `%*` argument but we needed to set it for both the `HKEY_CLASSES_ROOT\Applications\pythonxx.exe\shell\open\command` key as well as for the `HKEY_CLASSES_ROOT\py_auto_file\shell\open\command` key – jxramos Jan 13 '16 at 02:35
  • Thanks for your answer – Prashant Jan 05 '18 at 09:51
5

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
$ 
ObscureRobot
  • 7,306
  • 2
  • 27
  • 36