faqts : Computers : Programming : Languages : Python : Snippets

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

1 of 2 people (50%) answered Yes
Recently 0 of 1 people (0%) answered Yes

Entry

Options class

Jul 5th, 2000 10:02
Nathan Wallace, Hans Nowak, Snippet 237, Python Snippet Support Team


"""
Packages: miscellaneous
"""
""" options.py
    Defines an Options class for easy management of command line options.
    Example:
    o = Options("abd:fhlz")
    print o['a']    -> 1 if -a has been specified, else 0
    print o['d']    -> returns value after -d, if any
    print o['x']    -> error
    Setting default values:
    o['a'] = 1      (allowed)
    o['x'] = 1      (not allowed; x doesn't exist)
    o['a'] = "boo"  (not allowed; a is either 0 or 1)
    Other arguments (e.g. files):
    print o.args
"""
import getopt, sys
class Options:
    def __init__(self, tokens, args=sys.argv[1:]):
        self.tokens = tokens
        list = self._split(tokens)
        self.dict = {}
        self.args = []
        for elem in list:
            if len(elem) == 1:
                self.dict[elem] = 0
            else:
                self.dict[elem[0]] = ""
        self._getopt(args)
    def _getopt(self, args):
        opts, args = getopt.getopt(args, self.tokens)
        self.args = args[:]
        for opt, value in opts:
            oldvalue = self.dict[opt[1]]    # take 'a' from '-a', etc
            if type(oldvalue) == type(""):
                self.dict[opt[1]] = value
            else:
                self.dict[opt[1]] = 1
        #print self.dict
    def _split(self, tokens):
        list = []
        while tokens:
            option = tokens[0]
            tokens = tokens[1:]
            if tokens:
                if tokens[0] == ':':
                    option = option + ':'
                    tokens = tokens[1:]
            list.append(option)
        return list[:]
    def __getitem__(self, name):
        if name in self.dict.keys():
            return self.dict[name]
        else:
            raise "Options: name %s unknown" % (name)
    def __setitem__(self, name, value):
        if name in self.dict.keys():
            oldvalue = self.dict[name]
            if type(oldvalue) != type(value)    \
            or (type(oldvalue) == type(0) and value not in [0,1]):
                raise "Options: setting value `%s' for -%s not allowed" % (
                value, name)
            else:
                self.dict[name] = value
        else:
            raise "Options: setting value for -%s not allowed" % (name)
if __name__ == "__main__":
    o = Options("abcd:efg")
    # We can easily check if an option has been set:
    print o['a']
    print o['d']
    # Setting default values is legal, but only if the option is specified in
    # getopt:
    o['e'] = 1
    o['f'] = 'boo'