Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python will not read sys.argv

    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

like image 908
user1024028 Avatar asked Nov 01 '11 15:11

user1024028


People also ask

How do I pass SYS argv in Python?

How do I use SYS argv in Python script? To use, sys. argv in a Python script, we need to impo r t the sys module into the script. Like we import all modules, "import sys" does the job.

How does Sys argv work in Python?

sys. argv is the list of commandline arguments passed to the Python program. argv represents all the items that come along via the command line input, it's basically an array holding the command line arguments of our program. Don't forget that the counting starts at zero (0) not one (1).

How do I see the number of arguments passed in Python?

We will use len() function or method in *args in order to count the number of arguments of the function in python.

How do you pass arguments to a Python script?

In Python, arguments are passed to a script from the command line using the sys package. The argv member of sys ( sys. argv ) will store all the information in the command line entry and can be accessed inside the Python script. Python's getopt module can also be used to parse named arguments.


2 Answers

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/

like image 111
Juuso Ohtonen Avatar answered Sep 23 '22 14:09

Juuso Ohtonen


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
$ 
like image 23
ObscureRobot Avatar answered Sep 20 '22 14:09

ObscureRobot