Add "required" keyword to optparse.OptionParser.add_option()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import optparse
strREQUIRED = 'required'
class OptionWithDefault(optparse.Option):
ATTRS = optparse.Option.ATTRS + [strREQUIRED]
def __init__(self, *opts, **attrs):
if attrs.get(strREQUIRED, False):
attrs['help'] = '(Required) ' + attrs.get('help', "")
optparse.Option.__init__(self, *opts, **attrs)
class OptionParser(optparse.OptionParser):
def __init__(self, **kwargs):
kwargs['option_class'] = OptionWithDefault
optparse.OptionParser.__init__(self, **kwargs)
def check_values(self, values, args):
for option in self.option_list:
if hasattr(option, strREQUIRED) and option.required:
if not getattr(values, option.dest):
self.error("option %s is required" % (str(option)))
return optparse.OptionParser.check_values(self, values, args)
# demonstration of usage:
import sys
if __name__ == "__main__":
parser = OptionParser(usage="Demonstration of OptionParser with 'required' option")
parser.add_option("-i", "--input", required=True,
help="Input file")
dctOptions, lstArgs = parser.parse_args(sys.argv)
|
I know, "required option" is an oxymoron. However, I find this very helpful and I hope other people will also. Just add required=True to a call to OptionParser.add_option, and if the option value is None, an error is printed. Also, the help string for the option is prepended with "(Required) ".
Examples of running the above demonstration:
% ./extendedoptparse.py usage: Demonstration of OptionParser with 'required' option
extendedoptparse.py: error: option -i/--input is required
% ./extendedoptparse.py -h usage: Demonstration of OptionParser with 'required' option
options: -h, --help show this help message and exit -i INPUT, --input=INPUT (Required) Input file
Usage? A line showing simple usage would be appreciated.
For what it's worth, argparse (http://argparse.python-hosting.com/) supports required options out of the box, using the required= keyword argument to add_argument.
“Required option” is not an oxymoron if you think “required switch” instead.
“Optio” in Latine means “to choose”, and “option” retains this sense in some uses. At my university I get to select “mandatory options”, meaning I have to choose from a list. “Mandatory optional argument” is the oxymoron.
Cheers