Python Argparse-将参数的默认值设置为另一个参数
我添加了一个参数-c,现在我想添加另一个名为-ca的参数.如何将-ca的默认值设置为-c?我想做的是,如果未指定-ca,则将-c分配给-ca.
I've added a parameter -c, now I want to add another parameter called -ca. How can I set the default value of -ca as -c? What I want to do is if -ca is not specified, assign -c to -ca.
parser.add_argument("-c", type=str)
parser.add_argument("-ca", type=str, default=XXX)
谢谢.
通常,单破折号是单个字符.因此,-ca
是不明智的,尽管不是非法的.在正常的POSIX实践中,它可以解释为-c a
或-c -a
.
Normally, single dash flags are single characters. So -ca
is unwise, though not illegal. In normal POSIX practice it could be interpreted as -c a
or -c -a
.
还argparse
允许标记的参数(optionals
)以任何顺序出现.
Also argparse
allows flagged arguments (optionals
) to occur in any order.
通过分配所有默认值开始解析.遇到相关标志时,新值将覆盖默认值.按照这种顺序,一个参数不可能将另一个参数作为默认值.
Parsing starts out by assigning all the defaults. When the relevant flag is encountered, the new value overwrites the default. Given that order, it's impossible for one argument to take on the value of another as a default.
通常,参数之间的交互最好在解析后进行处理.有一个mutually_exclusive
分组,但没有mutually_inclusive
.您可以通过自定义的Action
类构建某种形式的交互,但是实现这一工作与任何后解析测试一样多.
In general interactions between arguments are best handled after parsing. There is a mutually_exclusive
grouping, but no mutually_inclusive
. You can build in some sort of interaction via custom Action
classes, but implementing that is just as much work as any post-parsing testing.
总而言之,最简单的方法是使用默认的default
,None
和测试
In sum, the simplest thing is to use the default default
, None
, and test
if args.ca is None:
args.ca = args.c