Python Argparse - 将参数的默认值设置为另一个参数 [英] Python Argparse - Set default value of a parameter to another parameter

查看:30
本文介绍了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.

总而言之,最简单的就是使用默认的defaultNone和test

In sum, the simplest thing is to use the default default, None, and test

if args.ca is None:
    args.ca = args.c

这篇关于Python Argparse - 将参数的默认值设置为另一个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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