parsing - Argparse: How to disallow some options in the presence of others - Python -
i have following utility:
import argparse parser = argparse.argumentparser(description='do action.') parser.add_argument('--foo', '--fo', type=int, default=-1, help='do foo') parser.add_argument('--bar', '--br', type=int, default=-1, help='do bar') parser.add_argument('--baz', '--bz', type=int, default=-1, help='do baz') parser.add_argument('--bat', '--bt', type=int, default=-1, help='do bat')
however, if --foo
option used, --bat
option should disallowed, , conversely, --bat
option should used if --bar
, --baz
present. how can accomplish using argparse
? sure, add bunch of if / else
blocks check that, there's built-in argparse
me?
you can create mutually-exclusive groups of options parser.add_mutually_exclusive_group
:
group = parser.add_mutually_exclusive_group() group.add_argument('--foo', '--fo', type=int, default=-1, help='do foo') group.add_argument('--bat', '--bt', type=int, default=-1, help='do bat')
, more complex dependency graphs (for example, --bat
requiring --bar
, --baz
), argparse
doesn't offer specific support. that'd going far in direction of inner-platform effect, trying rebuild of full generality of complete programming language within argparse
subsystem.
Comments
Post a Comment