FMc FMc - 24 days ago 8
Python Question

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

With Perl's

Getopt::Long
you can easily define command-line options that take a variable number of arguments:

foo.pl --files a.txt --verbose
foo.pl --files a.txt b.txt c.txt --verbose


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

Answer

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.