optparse question

James Mills prologic at shortcircuit.net.au
Mon Jan 26 20:16:25 EST 2009


On Tue, Jan 27, 2009 at 11:02 AM, Pat <Pat at junk.net> wrote:
(...)

> What does it take to pass single parameter to a program?
> http://docs.python.org/library/optparse.html stated that programs always
> have options.  Is that so?  What about "dir /s"?

Sample code:

----------------------------------------
#!/usr/bin/env python

"""optexample

Example of using optparse
"""

import os
import sys
import os.path
import optparse

__version__ = "0.1"

USAGE = "%prog [options] <arg>"
VERSION = "%prog v" + __version__

def parse_options():
    """parse_options() -> opts, args

    Parse and command-line options given returning both
    the parsed options and arguments.
    """

    parser = optparse.OptionParser(usage=USAGE, version=VERSION)

    parser.add_option("-v", "--verbose",
            action="store_true", default=False, dest="verbose",
            help="Verbose output during operation.")

    opts, args = parser.parse_args()
    if len(args) < 1:
        parser.print_help()
        raise SystemExit, 1

    return opts, args

def main():
    opts, args = parse_options()

    if opts.verbose:
        print args[0]

if __name__ == "__main__":
    main()
----------------------------------------

cheers
James



More information about the Python-list mailing list