[Tutor] Beginner puzzle with unpacking argv

Peter Lavelle lists at solderintheveins.co.uk
Thu Jun 16 20:52:03 CEST 2011


If you need to process command line arguments then the argparse module 
may also be useful to you. More info can be found here: 
http://docs.python.org/library/argparse.html

Regards

Peter Lavelle

On 16/06/11 19:03, Steve Willoughby wrote:
> 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).
>


-- 
LinkedIn Profile: http://linkedin.com/in/pmjlavelle
Twitter: http://twitter.com/pmjlavelle



More information about the Tutor mailing list