Processing multiple values for one single option using getopt/optparse? Processing multiple values for one single option using getopt/optparse? python python

Processing multiple values for one single option using getopt/optparse?


Yes, it can be done with optparse.

This is an example:

./test.py --categories=aaa --categories=bbb --categories ccc arg1 arg2 arg3

which prints:

arguments: ['arg1', 'arg2', 'arg3']options: {'categories': ['aaa', 'bbb', 'ccc']}

Full working example below:

#!/usr/bin/env pythonimport os, sysfrom optparse import OptionParserfrom optparse import Option, OptionValueErrorVERSION = '0.9.4'class MultipleOption(Option):    ACTIONS = Option.ACTIONS + ("extend",)    STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)    TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)    ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)    def take_action(self, action, dest, opt, value, values, parser):        if action == "extend":            values.ensure_value(dest, []).append(value)        else:            Option.take_action(self, action, dest, opt, value, values, parser)def main():    PROG = os.path.basename(os.path.splitext(__file__)[0])    long_commands = ('categories')    short_commands = {'cat':'categories'}    description = """Just a test"""    parser = OptionParser(option_class=MultipleOption,                          usage='usage: %prog [OPTIONS] COMMAND [BLOG_FILE]',                          version='%s %s' % (PROG, VERSION),                          description=description)    parser.add_option('-c', '--categories',                       action="extend", type="string",                      dest='categories',                       metavar='CATEGORIES',                       help='comma separated list of post categories')    if len(sys.argv) == 1:        parser.parse_args(['--help'])    OPTIONS, args = parser.parse_args()    print "arguments:", args    print "options:", OPTIONSif __name__ == '__main__':    main()

More information at http://docs.python.org/library/optparse.html#adding-new-actions


Despite the claims of the other comments, this is possible with vanilla optparse, at least as of python 2.7. You just need to use action="append". From the docs:

parser.add_option("-t", "--tracks", action="append", type="int")

If -t3 is seen on the command-line, optparse does the equivalent of:

options.tracks = []options.tracks.append(int("3"))

If, a little later on, --tracks=4 is seen, it does:

options.tracks.append(int("4"))


Sorry to come late to the party but I just solved this with optparse using the nargs flag.

parser.add_option('-c','--categories', dest='Categories', nargs=4 )

http://docs.python.org/2/library/optparse.html#optparse.Option.nargs

It is also worth noting, that argparse (suggested by unutbu) is now part of the standard python distribution while optparse is deprecated.