[python] Python Error: "ValueError: need more than 1 value to unpack"

In Python, when I run this code:

from sys import argv

script, user_name =argv
prompt = '>'

print "Hi %s, I'm the %s script." % (user_name, script)

I get this error:

Traceback (most recent call last):  
script, user_name =argv  
ValueError: need more than 1 value to unpack

What does that error mean?

This question is related to python arguments

The answer is


Probably you didn't provide an argument on the command line. In that case, sys.argv only contains one value, but it would have to have two in order to provide values for both user_name and script.


youre getting ''ValueError: need more than 1 value to unpack'', because you only gave one value, the script (which is ex14.py in this case)

the problem is, that you forgot to add a name after you ran the .py file.

line 3 of your code is

script, user_name = argv

the script is ex14.py, you forgot to add a name after

so if your name was michael,so what you enter into the terminal should look something like:

> python ex14.py michael

make this change and the code runs perfectly


You shouldn't be doing tuple dereferencing on values that can change like your line below.

 script, user_name = argv

The line above will fail if you pass less than one argument or more than one argument. A better way of doing this is to do something like this:

 for arg in argv[1:]:
     print arg

Of cause you will do something other than print the args. Maybe put a series of 'if' statement in the 'for' loop that set variables depending on the arguments passed. An even better way is to use the getopt or optparse packages.


I assume you found this code on Exercise 14: Prompting And Passing.

Do the following:

script = '*some arguments*' 
user_name = '*some arguments*'

and that works perfectly


You have to pass the arguments in the terminal in order to store them in 'argv'. This variable holds the arguments you pass to your Python script when you run it. It later unpacks the arguments and store them in different variables you specify in the program e.g.

script, first, second = argv
print "Your file is:", script
print "Your first entry is:", first
print "Your second entry is:" second

Then in your command line you have to run your code like this,

$python ex14.py Hamburger Pizza

Your output will look like this:

Your file is: ex14.py
Your first entry is: Hamburger
Your second entry is: Pizza

This error is because

argv # which is argument variable that is holding the variables that you pass with a call to the script.

so now instead

Python abc.py

do

python abc.py yourname {pass the variable that you made to store argv}


You should run your code in a following manner in order get your output,

python file_name.py user_name

You can't run this particular piece of code in the interactive interpreter. You'll need to save it into a file first so that you can pass the argument to it like this

$ python hello.py user338690