FMc FMc - 5 months ago 28
Python Question

With Python's optparse module, how do you create an option that takes a variable number of arguments?

With Perl's

you can easily define command-line options that take a variable number of arguments: --files a.txt --verbose --files a.txt b.txt c.txt --verbose

Is there a way to do this directly with Python's
module? As far as I can tell, the
option attribute can be used to specify a fixed number of option arguments, and I have not seen other alternatives in the documentation.


I believe optparse does not support what you require (not directly -- as you noticed, you can do it if you're willing to do all the extra work of a callback!-). You could also do it most simply with the third-party extension argparse, which does support variable numbers of arguments (and also adds several other handy bits of functionality).

This URL documents argparse's add_argument -- passing nargs='*' lets the option take zero or more arguments, '+' lets it take one or more arguments, etc.