extending optionparser to accept multiple comma delimited input for one arg

Peter Otten __peter__ at web.de
Fri Nov 27 09:33:59 CET 2009

cmptrwhz wrote:

> I have read the manual first of all :).  on using optionparser for the
> input of command line arguments and inputs.  I understand everything
> there was in the manual except how to extend the parser to accept a
> multiple list of input that is comma delimited....
> for example:
> ./convertContacts3.py -i a.vcf,b.vcf,c.vcf,d.vcf
> I want to be able to allow multiple filenames for one argument
> variable. Here is what I have so far and what I was wondering is how
> do I apply this subclass to the -i option so that it will gather the
> multiple filename inputs?

from optparse import OptionParser, Option

class MyOption (Option):
    ACTIONS = Option.ACTIONS + ("extend",)
    STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
    TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)

    def take_action(self, action, dest, opt, value, values, parser):
        if action == "extend":
            lvalue = value.split(",")
            values.ensure_value(dest, []).extend(lvalue)
                self, action, dest, opt, value, values, parser)

parser = OptionParser(option_class=MyOption)
parser.add_option("-i", "--input", action="extend")

options, args = parser.parse_args()
print options

If you had problems understanding the documentation perhaps you can suggest 
an improvement.


More information about the Python-list mailing list