[Tutor] Beginner puzzle with unpacking argv

Steve Willoughby steve at alchemy.com
Thu Jun 16 20:03:12 CEST 2011


On 16-Jun-11 10:10, Lisi wrote:

> 1 from sys import argv
> 2
> 3 script, user_name = argv
>
> I have tried every permutation of white space I could think of that might have
> looked like the original, but I always get the same error:

That will work ONLY if argv has at least 2 values in it.  Your source 
code is ok as far as it goes.  Try running your script with two command 
line arguments and see what you get.  (The first argument should be the 
name of your script, incidentally).

If your script were named foo.py, then running the command:
   > foo.py

would give you the error you see because argv only has 1 thing in it and 
you're trying to retrieve two.  If you ran it as:
   > foo.py bar

that should work, and script would be "foo.py" and user_name would be "bar".

You could check len(argv) first to see how many items you have before 
you try to get two values from it.

For more sophisticated argument handling, you could look at the optparse 
or argparse modules (but that's beyond the beginner level--something to 
keep in mind for later).

-- 
Steve Willoughby / steve at alchemy.com
"A ship in harbor is safe, but that is not what ships are built for."
PGP Fingerprint 4615 3CCE 0F29 AE6C 8FF4 CA01 73FE 997A 765D 696C


More information about the Tutor mailing list