Re: Arg decoding with a template?
by Skip Montanaro other posts by this author
Jul 31 2001 5:42PM messages near this date
Re: Arg decoding with a template?
|
Re: Arg decoding with a template?
Dale> It looks a bit unfriendly with all the - and -- but I'll see if I
Dale> can make some sense of it.
It's actually pretty easy to use once you learn the pattern. I commonly use
it like so:
alternate = ""
binary = quiet = verbose = 0
# split arg list up into pieces
try:
# colon after "a" says it needs an argument - others are boolean
# flags
opts, args = getopt.getopt(sys.argv[1:], "a:bqv")
except getopt.error:
usage()
# process the flags
for opt, arg in opts:
if opt == "-a":
alternate = arg
elif opt == "-b:
binary = 1
elif opt == "-q":
quiet = 1
elif opt == "-v":
verbose = 1
# process the rest of the args
if not args:
infile = sys.stdin
outfile = sys.stdout
if len(args) == 1:
infile = open(args[0])
outfile = sys.stdout
elif len(args) == 2:
infile = open(args[0])
outfile = open(args[1], "w")
else:
usage()
You can expand your getopt call to accept long args by adding a third
argument and adding the necessary tests to your for loop, but for internal
stuff I rarely do.
--
Skip Montanaro (skip@pobox.com)
http://www.mojam.com/
http://www.musi-cal.com/
--
http://mail.python.org/mailman/listinfo/python-list
Thread:
Dale Strickland-Clark
David Bolen
Jim Dennis
Marcin 'Qrczak' Kowalczyk
Chui Tey
David Bolen
Hans-Joachim Widmaier
Hans-Joachim Widmaier
Skip Montanaro
Quinn Dunkan
Dale Strickland-Clark
David Bolen
Steve Holden
David Bolen
Alex Martelli
Dale Strickland-Clark
Dale Strickland-Clark
Skip Montanaro
David Bolen
Peter Wang
Steve Holden
David Bolen
Steve Holden
Skip Montanaro
|