Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: argparse with optional command-line arguments

I'd like to implement arguments parsing.

./app.py -E [optional arg] -T [optional arg]

The script requires at least one of parameters: -E or -T

What should I pass in parser.add_argument to have such functionality?

UPDATE For some reason(s) the suggested solution with add_mutually_exclusive_group didn't work, when I added nargs='?' and const= attributes:

parser = argparse.ArgumentParser(prog='PROG')
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-F', '--foo', nargs='?', const='/tmp')
group.add_argument('-B', '--bar', nargs='?', const='/tmp')
parser.parse_args([])

Running as script.py -F still throws error:

PROG: error: one of the arguments -F/--foo -B/--bar is required

However, the following workaround helped me:

parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('-F', '--foo', nargs='?', const='/tmp')
parser.add_argument('-B', '--bar', nargs='?', const='/tmp')
args = parser.parse_args()

if (not args.foo and not args.bar) or (args.foo and args.bar):
   print('Must specify one of -F/-B options.')
   sys.exit(1)

if args.foo:
   foo_func(arg.foo)
elif args.bar:
   bar_func(args.bar)
...
like image 990
Mark Avatar asked Dec 05 '25 15:12

Mark


1 Answers

You can make them both optional and check in your code if they are set.

parser = argparse.ArgumentParser()
parser.add_argument('--foo')
parser.add_argument('--bar')

args = parser.parse_args()

if args.foo is None and args.bar is None:
   parser.error("please specify at least one of --foo or --bar")

If you want only one of the two arguments to be present, see [add_mutually_exclusive_group] (https://docs.python.org/2/library/argparse.html#mutual-exclusion) with required=True

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> group = parser.add_mutually_exclusive_group(required=True)
>>> group.add_argument('--foo', action='store_true')
>>> group.add_argument('--bar', action='store_false')
>>> parser.parse_args([])
usage: PROG [-h] (--foo | --bar)
PROG: error: one of the arguments --foo --bar is required
like image 109
Shashank V Avatar answered Dec 07 '25 03:12

Shashank V



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!