ActiveState Code

Recipe 573441: Extended optparse to allow definition of required options.


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

Python
 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)
    

Discussion

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

Comments

  1. 1. At 2:05 a.m. on 19 jun 2008, Shekhar Tiwatne said:

    Usage? A line showing simple usage would be appreciated.

  2. 2. At 11:16 a.m. on 3 aug 2008, Steven Bethard said:

    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.

Sign in to comment