views:

55

answers:

2

How can I define an option with an arbitrary number of arguments in Python's OptParser?

I'd like something like:

python my_program.py --my-option X,Y  # one argument passed, "X,Y"

python my_prgoram.py --my-option X,Y  Z,W  # two arguments passed, "X,Y" and "Z,W"

the nargs= option of OptParser limits me to a defined number. How can I do something like this?

parser.add_option("--my-options", dest="my_options", action="append", nargs="*")

which will simply take whatever's after --my-option and put it into a list? E.g. for case 1, it should be ["X,Y"], for case 2 it should be ["X,Y", "Z,W"].

What's a way to do this with OptParser?

thanks.

A: 

Have you tried ommitting the n_args bit? The examples in the docs suggest you don't need it.

Jon Cage
+2  A: 

The optarse module is deprecated in python 2.7 (which has just been released!). If you can upgrade, then you can use its replacement the argparse module. I think that has what you want. It supports a '*' value for nargs.

http://docs.python.org/library/argparse.html#nargs

PreludeAndFugue