A little disappointed so far
Duncan Booth
duncan at NOSPAMrcp.co.uk
Mon May 19 09:28:53 EDT 2003
Graham Nicholls <graham at rockcons.co.uk> wrote in
news:bg3ya.4397$573.2228 at news-binary.blueyonder.co.uk:
> How do I then handle the -o [filename case] I hate the idea of an
> "ignore_this_word" flag for the next time around the loop.
You had:
i=0
while (i < argc):
opt=arglist[i]
...
i += 1
Since you want to be able to pull out another argument, you want to iterate
over the list, but use an explicit iterator.
argiter = iter(arglist)
for opt in argiter:
if opt == '-o':
try:
filename = argiter.next()
except StopIteration:
error("-o requires another argument")
You could also handle the exception outside the for loop, as it could be
thrown for any option that needed an extra argument. Of course you really
should write this all in a more object-oriented manner, because it will be
cleaner and easier to maintain. It you don't want to use any of Python's
existing ways of processing arguments you could roll your own. Something
like this perhaps (untested code, so it undoubtedly has typos):
class Args:
def __init__(self, arglist):
self.debug = self.verbose = False
self.outfile = None
self.flist = []
argiter = iter(arglist)
self.progname = argiter.next()
for opt in argiter:
if opt.startswith('-'):
handler = 'opt_' + opt[1]
handlerfn = getattr(self, handler, badOption)
try:
handlerfn(opt, argiter)
except StopIteration:
usage("Option %s expected another argument" % opt)
sys.exit(BAD_ARGS)
else:
self.notAnOption(opt)
def opt_d(self, opt, argiter):
print "%s DEBUG - debug activated" % progname
self.debug=True
def opt_v(self, opt, argiter):
self.verbose=True
print "%s version %s" % (progname,version)
def opt_o(self, opt, argiter):
self.outfile = argiter.next()
if outfile.startswith('-'):
raise StopIteration
def badOption(self, opt, argiter):
usage("Unknown option %s" % opt)
sys.exit(BAD_ARGS)
def notAnOption(self, arg):
self.flist.append(arg)
and then the rest of your code does:
args = Args(sys.argv)
infiles, outfile = args.flist, args.outfile
... etc.
--
Duncan Booth duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?
More information about the Python-list
mailing list