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

查看:244
本文介绍了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和测试

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天全站免登陆