Python optparse defaults and explicit parameters

Take the following pretty standard code:

from optparse import OptionParser opts = OptionParser() opts.add_option('-f', action="store_true") opts.add_option("-x", dest="x", type="int", default=1) options, args = opts.parse_args() 

Suppose that -x and -f are mutually exclusive: when -x and -f both explicitly present, an error should be reported.

How to determine if -x is present explicitly? Even if this is not the case, specify the default value.

One way is to avoid setting a default value, which I would rather not do, because --help nicely displays the default values.

Another way would be to check sys.argv for instances of -x , which is also a bit inconvenient if there is more than one name for -x (i.e., -long-name) and there are more than one pair of mutually exclusive options.

Is there an elegant solution for this?

+6
source share
2 answers

Use argparse . There is a section for mutually exclusive groups :

argparse.add_mutually_exclusive_group (required = False)

Create a mutually exclusive group. argparse will verify that only one of the arguments is present in a mutually exclusive group on the command line:

 >>> parser = argparse.ArgumentParser(prog='PROG') >>> group = parser.add_mutually_exclusive_group() >>> group.add_argument('--foo', action='store_true') >>> group.add_argument('--bar', action='store_false') >>> parser.parse_args(['--foo']) Namespace(bar=True, foo=True) >>> parser.parse_args(['--bar']) Namespace(bar=False, foo=False) >>> parser.parse_args(['--foo', '--bar']) usage: PROG [-h] [--foo | --bar] PROG: error: argument --bar: not allowed with argument --foo 

optparse is still not recommended.

+7
source

You can accomplish this with optparse with a callback. Create your code:

 from optparse import OptionParser def set_x(option, opt, value, parser): parser.values.x = value parser.values.x_set_explicitly = True opts = OptionParser() opts.add_option('-f', action="store_true") opts.add_option("-x", dest="x", type="int", default=1, action='callback', callback=set_x) options, args = opts.parse_args() opts.values.ensure_value('x_set_explicitly', False) if options.x_set_explicitly and options.f: opts.error('options -x and -f are mutually exclusive') 

Let me call this script op.py now. If I do python op.py -x 1 -f , the answer will be as follows:

Usage: op.py [options]

op.py: error: the -x and -f options are mutually exclusive

+8
source

Source: https://habr.com/ru/post/900993/


All Articles