My code:
from sys import argv
pl_magic, pl_pet = argv
pl_enemy = raw_input("The second enchanter:")
print "The most powerful enchanter is",pl_magic
print pl_pet,"is the pet of",pl_magic
print "They hate %s" %pl_enemy
Output in powershell:
PS D:\FILE\LPHW> python ex13b.py 1 2 3
Traceback (most recent call last):
File "ex13b.py", line 2, in <module>
pl_magic, pl_pet = argv
ValueError: too many values to unpack
I'm wondering what's wrong with the code....
Argv array contains not only command-line arguments but also name of the running script so
argv[0] = "ex13b.py"
Also, by writing
pl_magic, pl_pet = argv
you are expecting argv to contain only 2 values while in command-line arguments you are giving 3 arguments. That makes argv contain a total of 4 values because the first value is always script name.
Your code should look something like this:
script_name, pl_magic, pl_pet, third_argument = argv
That being said, you shouldn't just try to unpack things blindly but also add some checks for example:
args_count = len(argv) - 1
if args_count < 3:
#do something if not enough arguments provided
When you do:
pl_magic, pl_pet = argv
And enter the parameters (remember, you should take the filename into account in sys.argv
):
ex13b.py 1 2 3
You actually run the following line:
pl_magic, pl_pet = ['ex13b.py', '1', '2', '3']
When unpacking values into variables, you need the same number of variables and values. This is why your code won't work.
You can use:
_, par1, par2, par3 = sys.argv
In Python 3 you can also use:
_, par1, *par2 = sys.argv
Which will result in:
_ = 'ex13b.py'
par1 = '1'
par2 = ['2', '3']
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.