posparse is a Python module to parse command line positional arguments, extending the optparse module. optparse is able to parse command line options like -a or --a=foo but all positional arguments are simply returned as a sequence.
posparse defines a PositionalParser class that is a drop-in replacement for optparse's OptionParser. Indeed, all symbols exported by from optparse import * are available when importing posparse.
To use PositionalParser, import posparse, create and instance of PositionalParser, add command line options as usual, add positional arguments formats and call the parse_args method, as is shown in the following example:
import posparse
parser = posparse.PositionalParser()
parser.add_option("-v", dest = "verbose", action = "store_true", default = False)
parser.add_positional_format([])
parser.add_positional_format([
posparse.make_positional("start", dest = "action", action = "store_const",
const = "start"),
posparse.make_positional(dest = "filename"),
posparse.make_positional(dest = "priority", type = "int")
])
parser.add_positional_format([
posparse.make_positional("stop", dest = "action", action = "store_const",
const = "stop"),
])
options, args = parser.parse_args()
print "Verbose: %s" % options.verbose
if hasattr(args, "action"):
print "Action: %s" % args.action
if args.action == "start":
print "Filename: %s" % args.filename
print "Priority: %d" % args.priority
parse_args first parses the command line options. Then it takes the remaining positional arguments and parse them according to the defined positional arguments formats until it gets a match (no missing or superfluous arguments, and no type mismatches). It then returns an object with the options values and an object with the values stored by the matched positional arguments.
This is what you get when running the script:
$ sample.py -v start foo.txt 12 Verbose: True Action: start Filename: foo.txt Priority: 12 $ sample.py stop Verbose: False Action: stop $ sample.py Verbose: False $ sample.py -v wrong usage: sample.py [options] sample.py: error: invalid positional arguments
This module is BSD-licensed, copyrighted by Diogo Kollross. Mail me if you have questions or suggestions.