Iterating over multiple lists (a newbie question)

Greg Jorgensen gregj at pobox.com
Thu Jan 4 19:50:32 EST 2001


Here's a somewhat generalized parser for simple argument/parameter strings
like command lines. You'll probably want to make it into a function or a
class for real-world use.

--
Greg Jorgensen
PDXperts
Portland, Oregon, USA
gregj at pobox.com



# command line or other string to parse
commandline = '-log -port 25 -file -debug -bogus dummy'

# args is keyed by the valid argument names
# args[arg] = 1 if -arg expects a parameter, else args[arg] = 0
args = { 'debug':0, 'port':1, 'file':1, 'log':0 }

# argp will contain the parsed argument list
# add any default values to argp here
argp = {'log':0, 'port':20}

errmsg = ''
paramkey = ''
for a in commandline.split():
    if a[0] == '-':                 # -argument
        a = a[1:].lower()
        p = args.get(a, -1)         # get parameter flag, default to 0
        paramkey = ''
        if p == 1:                  # next parameter will be associated with
args[a]
            paramkey = a
        elif p == 0:                # no parameter expected
            argp[a] = ''
        else:
            errmsg += 'unexpected argument: -%s\n' % a
    else:                           # parameter found...
        if paramkey:                # which argument does it belong to?
            argp[paramkey] = a
            paramkey = ''
        else:
            errmsg += 'unexpected value: %s\n' % a

# let's see the result
if errmsg:
    print 'errors:\n' + errmsg

print 'parsed arguments:'
for e in argp.keys():
    if argp[e]:
        print '-%s %s' % (e, argp[e]),
    else:
        print '-%s' % e,

print '\n'





More information about the Python-list mailing list