Table of Contents

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 `self.opts` dict, but this isn't required; it's only for consistency. A few example command lines that will work:

# XXX - Where'd the examples go?

Imported modules |
--- | ---
import getopt import new import os from os import path import reflect import string import sys import text import util
Functions |
docMakeChunks
| docMakeChunks

    docMakeChunks ( optList,  width=80 )

### Makes doc chunks for option declarations.

Takes a list of dictionaries, each of which may have one or more of the keys `long`, `short`, `doc`, `default`, `optType`.

Returns a list of strings. The strings may be multiple lines, all of them end with a newline.

Classes |

Options | A class which can be subclassed to provide command-line options
UsageError |

Table of Contents

This document was automatically generated on Sat Apr 20 01:31:23 2002 by HappyDoc version 2.0