Python: How to make an option to be required in optparse?

62,190

Solution 1

You can implement a required option easily.

parser = OptionParser(usage='usage: %prog [options] arguments')
parser.add_option('-f', '--file', 
                        dest='filename',
                        help='foo help')
(options, args) = parser.parse_args()
if not options.filename:   # if filename is not given
    parser.error('Filename not given')

Solution 2

Since if not x doesn't work for some(negative,zero) parameters,

and to prevent lots of if tests, i preferr something like this:

required="host username password".split()

parser = OptionParser()
parser.add_option("-H", '--host', dest='host')
parser.add_option("-U", '--user', dest='username')
parser.add_option("-P", '--pass', dest='password')
parser.add_option("-s", '--ssl',  dest='ssl',help="optional usage of ssl")

(options, args) = parser.parse_args()

for r in required:
    if options.__dict__[r] is None:
        parser.error("parameter %s required"%r)

Solution 3

On the help message of each required variable Im writting a '[REQUIRED]' string at the beggining, to tag it to be parsed later, then I can simply use this function to wrap it around:

def checkRequiredArguments(opts, parser):
    missing_options = []
    for option in parser.option_list:
        if re.match(r'^\[REQUIRED\]', option.help) and eval('opts.' + option.dest) == None:
            missing_options.extend(option._long_opts)
    if len(missing_options) > 0:
        parser.error('Missing REQUIRED parameters: ' + str(missing_options))

parser = OptionParser()
parser.add_option("-s", "--start-date", help="[REQUIRED] Start date")
parser.add_option("-e", "--end-date", dest="endDate", help="[REQUIRED] End date")
(opts, args) = parser.parse_args(['-s', 'some-date'])
checkRequiredArguments(opts, parser)

Solution 4

The current answer with the most votes would not work if, for example, the argument were an integer or float for which zero is a valid input. In these cases it would say that there is an error. An alternative (to add to the several others here) would be to do e.g.

parser = OptionParser(usage='usage: %prog [options] arguments')
parser.add_option('-f', '--file', dest='filename')
(options, args) = parser.parse_args()
if 'filename' not in options.__dict__:
  parser.error('Filename not given')

Solution 5

I'm forced to use python 2.6 for our solution so I'm stick to optparse module. Here is solution I found to check for required options that works without specifying second time list of required options. Thus when you add new option you don't have to add it's name into the list of options to check.

My criteria for required option - option value should be not None and this options doesn't have default (user didn't specified add_option(default="...",...).

def parse_cli():
    """parse and check command line options, shows help message
    @return: dict - options key/value
    """
    import __main__
    parser = OptionParser(description=__main__.__doc__)
    parser.add_option("-d", "--days", dest="days",
                      help="Number of days to process")
    parser.add_option("-p", "--period", dest="period_length",default="2",
              help="number or hours per iteration, default value=%default hours")    
    (options, args) = parser.parse_args()

    """get dictionary of options' default values. 
       in this example: { 'period_length': '2','days': None}"""
    defaults = vars(parser.get_default_values())
    optionsdict = vars(options)

    all_none = False        
    for k,v in optionsdict.items():
        if v is None and defaults.get(k) is None:
            all_none = True


    if all_none:
        parser.print_help()
        sys.exit()
    return optionsdict
Share:
62,190
jack
Author by

jack

Updated on July 28, 2022

Comments

  • jack
    jack almost 2 years

    I've read this http://docs.python.org/release/2.6.2/library/optparse.html

    But I'm not so clear how to make an option to be required in optparse?

    I've tried to set "required=1" but I got an error:

    invalid keyword arguments: required

    I want to make my script require --file option to be input by users. I know that the action keyword gives you error when you don't supply value to --file whose action="store_true".

  • user225312
    user225312 over 13 years
    @Ant: Yeah I know but the brackets signify that parser.parse_args() returns a tuple, so I let them stay!
  • ha9u63ar
    ha9u63ar over 9 years
    Does this mean "required" option is only with argparse, but not optparse? The answer is good though, I don't see why this cannto be accepted?
  • PatriceG
    PatriceG over 8 years
    The optparse module is deprecated since version 2.7. Example with argparse here: stackoverflow.com/questions/7427101/…
  • Tom
    Tom over 7 years
    So If Im understanding this properly, is optparse just older than argparse?
  • nealmcb
    nealmcb over 7 years
    Nice - thank you. But to speed it up and avoid the need to import re, use the string startwith method like this: if option.help.startswith('[REQUIRED]')...
  • Pankaj Garg
    Pankaj Garg almost 7 years
    For option group, you can use the following: for group in parser.option_groups:...
  • Manoj Sahu
    Manoj Sahu almost 6 years
    this is for argument parser not for option parser