Python Argparse - Set default value of a parameter to another parameter

╄→尐↘猪︶ㄣ 提交于 2020-05-13 11:46:31

问题


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)

Thanks.


回答1:


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.

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.

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.

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

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


来源:https://stackoverflow.com/questions/45686317/python-argparse-set-default-value-of-a-parameter-to-another-parameter

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