需要 python argparse add_argument_group [英] python argparse add_argument_group required

查看:27
本文介绍了需要 python argparse add_argument_group的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个问题中

argparse:需要两个参数之一

argparse: require either of two arguments

我找到了我想要的解决方案的参考,但它不正确.

I find a reference to the solution I want, but it isn't right.

我需要至少提供 2 个选项中的 1 个,option1、option2 或两者...

I need at least 1 of 2 options to be present, option1, option2 or both...

add_argument_group 函数没有必需的参数.add_mutually_exclusive 函数有它,但它迫使我在 2 个选项之间进行选择,这不是我想要的.

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,

推荐答案

argument_group 只是控制帮助显示.它不影响解析或检查错误.mutually_exclusive_group 影响使用显示和出现测试,但正如你所注意到的,它的逻辑不是你想要的.

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.

存在一个 Python 错误问题,需要某种形式的嵌套包含"组.但是允许嵌套和所有版本的和/或/异或逻辑的通用形式并不是一个微不足道的补充.

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.

我认为您最简单的解决方案是在解析后测试 args.如果默认值组合错误,则引发错误.

I think your simplest solution is to test the args after parsing. If there is a wrong mix of defaults, then raise an error.

假设两个参数的默认值都是None:

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')

什么是有意义的用法行?必需的互斥'用途(opt1 | opt2).(opt1 & opt2)可能表明两者都是必需的.您的情况是非排他性或`

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)

这篇关于需要 python argparse add_argument_group的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆