Welcome, guest | Sign In | My Account | Store | Cart

Add "required" keyword to optparse.OptionParser.add_option()

Python, 31 lines
 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

3 comments

Shekhar Tiwatne 13 years, 5 months ago  # | flag

Usage? A line showing simple usage would be appreciated.

Steven Bethard 13 years, 3 months ago  # | flag

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.

Éric Araujo 11 years, 8 months ago  # | flag

“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

Created by Alec Wysoker on Wed, 4 Jun 2008 (PSF)
Python recipes (4591)
Alec Wysoker's recipes (1)

Required Modules

Other Information and Tasks