Python will not read sys.argv
Asked Answered
C

2

8
    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

Chopine answered 1/11, 2011 at 15:59 Comment(3)
What happens when you just print sys.argv? And does it work, when calling the file via python.exe myfile.py helloworld?Buckshot
ah, thanks for your responces, managed to get it working. had a very silly mistake, didnt add python to the Path in system variablesChopine
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.Chokefull
D
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
$ 
Devotional answered 1/11, 2011 at 16:9 Comment(0)
I
24

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/

Incommensurate answered 16/7, 2014 at 12:47 Comment(2)
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 keyGiliana
This completely solved the problems I had passing command line args to Python 3.10.7 (which I installed using Scoop). I wonder how on Earth the person who originally found this solution, found it.Drongo
D
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
$ 
Devotional answered 1/11, 2011 at 16:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.