Arguments that are dependent on other arguments with Argparse
After you call parse_args
on the ArgumentParser
instance you've created, it'll give you a Namespace
object. Simply check that if one of the arguments is present then the other one has to be there too. Like:
args = parser.parse_args()
if ('LoadFiles' in vars(args) and
'SourceFolder' not in vars(args) and
'SourceFile' not in vars(args)):
parser.error('The -LoadFiles argument requires the -SourceFolder or -SourceFile')
You can use subparsers in argparse
import argparse
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('--foo', required=True, help='foo help')
subparsers = parser.add_subparsers(help='sub-command help')
# create the parser for the "bar" command
parser_a = subparsers.add_parser('bar', help='a help')
parser_a.add_argument('bar', type=int, help='bar help')
print(parser.parse_args())
There are some argparse
alternatives which you can easily manage cases like what you mentioned.
packages like:
click or
docopt.
If we want to get around the manual implementation of chain arguments in argparse, check out the Commands and Groups in click for instance.