How to allow argparse to check mutually exclusive argument groups

I have test code as follows, which should take the positional argument file OR all the optional arguments time , expression and name :

 import argparse parser = argparse.ArgumentParser() parser.add_argument("-t","--time") parser.add_argument("-x","--expression") parser.add_argument("-n","--name") parser.add_argument("file") print parser.parse_args() 

The following combination should work

 test.py filename test.py -t 5 -x foo -n test 

but NOT these:

 test.py filename -t 5 # should raise error because the positional and the optional -t argument cannot be used together test.py -t 5 -x foo # should raise an error because all three of the optional arguments are required 

Any simple solution to this problem?

+4
source share
2 answers

The first problem is that you indicated that the file is positional, which will require it. You will probably need to convert it to an optional argument.

Here is an easy way to verify that the arguments are correct:

 import argparse parser = argparse.ArgumentParser() parser.add_argument("-t","--time") parser.add_argument("-x","--expression") parser.add_argument("-n","--name") parser.add_argument("-f", "--file") args = parser.parse_args() has_file = args.file is not None has_txn = None not in frozenset([args.time, args.expression, args.name]) assert (has_file ^ has_txn), "File or time, expression and name must be provided" 
+2
source

You may be interested in the following approach.

 import argparse, sys print(sys.argv) if len(sys.argv) == 2: sys.argv += ['-t', 'time', '-x', 'expression', '-n', 'name'] else: sys.argv.append('FILE') parser = argparse.ArgumentParser() group = parser.add_argument_group('Required Group', 'All 3 are required else provide "file" argument.') group.add_argument("-t","--time", required=True) group.add_argument("-x","--expression", required=True) group.add_argument("-n","--name", required=True) parser.add_argument("file", help='file name') print(parser.parse_args()) 

Here is an example output.

 $ ./t.py -t 2 -x "a + b" -n George ['./t.py', '-t', '2', '-x', 'a + b', '-n', 'George'] Namespace(expression='a + b', file='FILE', name='George', time='2') $ ./t.py FILE ['./t.py', 'FILE'] Namespace(expression='expression', file='FILE', name='name', time='time') $ ./t.py -h usage: t.py [-h] -t TIME -x EXPRESSION -n NAME file positional arguments: file file name optional arguments: -h, --help show this help message and exit Required Group: All 3 are required else provide "file" argument. -t TIME, --time TIME -x EXPRESSION, --expression EXPRESSION -n NAME, --name NAME 
0
source

All Articles