Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using command line arguments in Python: Understanding sys.argv

I'm currently going through Learn Python The Hard Way. I think this example might be out dated so I wanted to get feedback here on it.

I'm using Python 3.1

from sys import argv

script, first, second, third = argv

print("the script is called:", (script))
print("your first variable is:", (first))
print("your second variable is:", (second))
print("your third variable is:", (third))

I'm getting this error:

Traceback (most recent call last):
  File "/path/ch13.py", line 3, in <module>
    script, first, second, third, bacon = argv
ValueError: need more than 1 value to unpack

Any idea what's wrong?

like image 379
Zack Shapiro Avatar asked Jan 21 '11 23:01

Zack Shapiro


People also ask

How do you use SYS arguments in Python?

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. Ideally, we want this at the top of the script, but anywhere before we use the sys.

What is argv in command line argument?

The second parameter, argv (argument vector), is an array of pointers to arrays of character objects. The array objects are null-terminated strings, representing the arguments that were entered on the command line when the program was started.

How do you use command line in Python?

Execute the Python code in command. command can be one or more statements separated by newlines, with significant leading whitespace as in normal module code. If this option is given, the first element of sys. argv will be "-c" and the current directory will be added to the start of sys.


2 Answers

You forgot to pass arguments to the script, e.g. foo.py bar baz quux.

enter image description here

like image 197
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 19:10

Ignacio Vazquez-Abrams


In order to pass arguments, you will need to run the script in this manner:

python fileName.py argument1 argument2

Depending on how many variables you have = to argv, this is how many you need to have minus the first argument (script). E.g.,

 script, first, second, third = argv

should have 3 arguments.

like image 36
Fred Avatar answered Oct 02 '22 19:10

Fred