问题
In this question
argparse: require either of two arguments
I find a reference to the solution I want, but it isn't right.
I need at least 1 of 2 options to be present, option1, option2 or both...
The add_argument_group function doesn't have a required argument. The add_mutually_exclusive function has it, but it forces me to choose between the 2 options, which is not what I want.
rds,
回答1:
argument_group
just controls the help display. It does not affect the parsing or check for errors. mutually_exclusive_group
affects usage display and tests for occurrence, but as you note, its logic is not what you want.
There is a Python bug issue requesting some form of nested 'inclusive' group. But a general form that allows nesting and all versions of and/or/xor logic is not a trivial addition.
I think your simplest solution is to test the args
after parsing. If there is a wrong mix of defaults, then raise an error.
Assuming the default for both arguments is None
:
if args.option1 is None and args.option2 is None:
parser.error('at least one of option1 and option2 is required')
What would be meaningful usage line? required mutually exclusive' uses
(opt1 | opt2).
(opt1 & opt2)might indicate that both are required. Your case is a
non-exclusive or`
usage: PROG [-h] (--opt1 OPT1 ? --opt2 OPT2)
来源:https://stackoverflow.com/questions/27258173/python-argparse-add-argument-group-required