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?
sys.arg
is a list of command line parameters. You need to actually pass command line parameters to the script to populate this list. Do this either in your IDE's project settings or by running like this on the command line:Note that the first argument is always the script's name (
python script.py
in this case). Due to your usage of unpacking, you will get aValueError
whenever you pass fewer or more than 3 parameters. You can check the number before unpacking usinglen(argv)-1
and presenting a suitable error if not 3.On a related note, look at
getopt
if you need to do more complex argument passing.In order to run this script on the command line, you need to use three arguments. You will have to type something similar to the following:
Save this script as: s.py
Run this script from terminal as follows:
In order to pass arguments, you will need to run the script in this manner:
Depending on how many variables you have = to
argv
, this is how many you need to have minus the first argument (script). E.g.,should have 3 arguments.