Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 923
FMc Avatar asked Jun 22 '09 01:06

FMc


People also ask

How do you create an argument in Python?

To add arguments to Python scripts, you will have to use a built-in module named “argparse”. As the name suggests, it parses command line arguments used while launching a Python script or application. These parsed arguments are also checked by the “argparse” module to ensure that they are of proper “type”.

How do you take options in Python?

Python getopt function args: List of arguments to be passed. options: String of option letters that the script wants to recognize. Options that require an argument should be followed by a colon (:). long_options: List of the string with the name of long options.


1 Answers

This took me a little while to figure out, but you can use the callback action to your options to get this done. Checkout how I grab an arbitrary number of args to the "--file" flag in this example.

from optparse import OptionParser,

def cb(option, opt_str, value, parser):
        args=[]
        for arg in parser.rargs:
                if arg[0] != "-":
                        args.append(arg)
                else:
                        del parser.rargs[:len(args)]
                        break
        if getattr(parser.values, option.dest):
                args.extend(getattr(parser.values, option.dest))
        setattr(parser.values, option.dest, args)

parser=OptionParser()
parser.add_option("-q", "--quiet",
        action="store_false", dest="verbose",
        help="be vewwy quiet (I'm hunting wabbits)")
parser.add_option("-f", "--filename",
        action="callback", callback=cb, dest="file")

(options, args) = parser.parse_args()

print options.file
print args

Only side effect is that you get your args in a list instead of tuple. But that could be easily fixed, for my particular use case a list is desirable.

like image 100
Dave Rawks Avatar answered Oct 13 '22 21:10

Dave Rawks