unpack sequence to tuple?
Magnus Lie Hetland
mlh at idi.ntnu.no
Sat Jan 27 19:03:00 EST 2001
<noahspurrier at my-deja.com> wrote in message
news:94j6j1$3na$1 at nnrp1.deja.com...
> I want to easily read arguments in a sequence into separate variables.
> Basically, I want to use a Per1 idiom and do this:
>
> (cmd, host, user, key) = tuple(sys.argv)
[...]
> This is not a big deal. It's certainly not unclear to simply read
> each element, but I was hoping that there might be something short
> and neat that would already do this:
> host = sys.argv[1]
> user = sys.argv[2]
> key = sys.argv[3]
Here you would (of course) also get an exception if sys.argv didn't
contain all the elements you were after (i.e. no None-padding)...
A standard thing in many programs is to check if the number of
required args are available:
if len(sys.argv) == 4:
cmd, host, user, key = sys.argv
else:
print >> sys.stderr, "usage: foobar <host> <user> <key>
sys.exit(1)
That's how I would do it, at least.
And if you allow more arguments, you can simply do this:
if len(sys.argv >= 4:
host, user, key = sys.argv[1:4]
else:
print >> sys.stderr, "usage: foobar <host> <user> <key> [<spam> ...]"
sys.exit(1)
Here I have also excluded cmd (which can, of course, be done in the
first as well), since you don't seem to want that.
>
> Yours,
> Noah
--
Magnus Lie Hetland (magnus at hetland dot org)
"Reality is what refuses to disappear when you stop
believing in it" -- Philip K. Dick
More information about the Python-list
mailing list