问题
I have the following utility:
import argparse
parser = argparse.ArgumentParser(description='Do some action.')
parser.add_argument('--foo', '--fo', type=int, default=-1, help='do something foo')
parser.add_argument('--bar', '--br', type=int, default=-1, help='do something bar')
parser.add_argument('--baz', '--bz', type=int, default=-1, help='do something baz')
parser.add_argument('--bat', '--bt', type=int, default=-1, help='do something bat')
However, if the --foo option is used, the --bat option should be disallowed, and conversely, the --bat option should only be used if --bar and --baz are present. How can I accomplish that using argparse? Sure, I could add a bunch of if / else blocks to check for that, but there's something built-in argparse that could do that for me?
回答1:
You can create mutually-exclusive groups of options with parser.add_mutually_exclusive_group:
group = parser.add_mutually_exclusive_group()
group.add_argument('--foo', '--fo', type=int, default=-1, help='do something foo')
group.add_argument('--bat', '--bt', type=int, default=-1, help='do something bat')
, but for more complex dependency graphs (for example, --bat requiring --bar and --baz), argparse doesn't offer any specific support. That'd be going too far in the direction of the inner-platform effect, trying to rebuild too much of the full generality of a complete programming language within the argparse subsystem.
来源:https://stackoverflow.com/questions/39459015/argparse-how-to-disallow-some-options-in-the-presence-of-others-python