Module: usage | Twisted-0.17.4/twisted/python/usage.py | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
twisted.python.usage is a module for parsing/handling the command line of your program. You use it by subclassing Options with certain methods/attributes defined. Here's an example: from twisted.python import usage import sys class MyOptions(usage.Options): optFlags = [['hello', 'h'], ['goodbye', 'g']] optParameters = [['message', 'm', 'friend!']] def __init__(self): usage.Options.__init__(self) self.opts['debug'] = 0 def opt_debug(self, opt): if opt == 'yes' or opt == 'y' or opt == '1': self.opts['debug'] = 1 elif opt == 'no' or opt == 'n' or opt == '0': self.opts['debug'] = 0 else: print 'Unknown value for debug, setting to 0' self.opts['debug'] = 0 opt_d = opt_debug # a single-char alias for --debug try: config = MyOptions() config.parseOptions() except usage.UsageError, ue: print '%s: %s' % (sys.argv[0], ue) if config.opts['hello']: if config.opts['debug']: print 'printing hello' print 'hello', config.opts['message'] #defaults to 'friend!' if config.opts['goodbye']: if config.opts['debug']: print 'printing goodbye' print 'goodbye', config.opts['message'] #EOF As you can see, you define optFlags as a list of parameters (with both long and short names) that are either on or off. optParameters are parameters with string values, with their default value as the third parameter in the list. If you want to handle your own options, define a method named opt_paramname
that takes (self, option) as arguments. option will be whatever immediately
follows the parameter on the command line. You should place any option-related
state in the # XXX - Where'd the examples go?
|