python argparse add_argument_group required

我们两清 提交于 2019-12-11 02:24:34

问题


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 anon-exclusive or`

usage: PROG [-h] (--opt1 OPT1 ? --opt2 OPT2)


来源:https://stackoverflow.com/questions/27258173/python-argparse-add-argument-group-required

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!