command-line parser

Ben Wolfson rumjuggler at cryptarchy.org
Sun Jun 18 19:15:18 EDT 2000


On Sun, 18 Jun 2000 15:11:25 -0700, Trent Mick <trentm at activestate.com>
wrote:


> Some comments below.
[comments excised].

Some advice taken, and it's a lot more readable, or seems so to me.
An instance of the Option class can take a callback that gets called on its
value, so if a particular option's value needs to be an int, say, you could
instantiate it with

Option(<short>, <long>, 1, val_cb = int)

If the callback raises an exception, the option's help() function prints
its description

# arglist.py
class Error(Exception):
    pass

class Option:
    def __init__(self, short, long=None, has_value=None, default_value =\
                 None, val_cb = None, description = None):
        self.short = short
        self.long = long
        self.has_val = has_value
        self.val_cb = val_cb
        self.value = default_value or None
        self.description = description
        
    def get_keys(self):
        return self.short, self.long
    
    def handle(self, val):
        if self.has_val:
            if val:
                self.value = val
            elif self.value is None:
                    raise Error, 'Option %s requires a value' % opt
        else:
            self.value = 1
        if self.val_cb:
            try:
                self.value = self.val_cb(self.value)
            except:
                self.help()
        del self.short, self.long, self.val_cb, self.has_val

    def help(self):#rather simpleminded, yes?
        if self.description:
            print
            print self.description
    
        
class Arguments:
    def __init__(self, *opts):
        self.__dict__['nonopts'] = []
        self.__dict__['dict'] = {}
        for opt in opts:
            short, long = opt.get_keys()
            if short and long:
                self.dict[short] = self.dict[long] = opt
            elif short:
                self.dict[short] = opt
            else:
                self.dict[long] = opt

    def process(self, options):
        for opt in options:
            if opt[0] <> '-':
                self.nonopts.append(opt)
                options.remove(opt)
        for opt,val in map(splitstrip, options):
            self.dict[opt].handle(val)

    def __getattr__(self, key):
        if not self.dict.has_key(key):
            raise Error, 'No option %s' % key
        return self.dict[key].value

    def get_nonopts(self):
        return self.nonopts
            

def splitstrip(opt):
    return optsplit(optstrip(opt))

def optstrip(opt):
    while opt[0] == '-':
        opt = opt[1:]
    return opt

def optsplit(opt):
    if ':' in opt:
        return opt.split(':',2)
    elif '=' in opt:
        return opt.split('=',2)
    return opt, None



More information about the Python-list mailing list