是否可以根据其他可选参数将 argparse 的可选参数设置为默认值? [英] Is it possible to set argparse's optional argument to a default value based on other optional argument?
问题描述
我正在使用 argparse
并且我有两个可选参数:
I am using argparse
and I have two optional arguments:
parser.add_argument('-a', '--arg1', default=1, type=int)
parser.add_argument('-b', '--arg2', action='store_true', default=False)
是否只有在 arg2
设置为 True
时才可以将 arg1
默认值设置为1"?
Is there a way to set arg1
default value of "1" if only if arg2
is set True
?
换句话说,我只想在 arg2
设置为 True
时执行以下操作:
In other word, I only want to do the following only if arg2
is set to True
:
parser.add_argument('-a', '--arg1', default=1, type=int)
否则将设置为:
parser.add_argument('-a', '--arg1', type=int)
推荐答案
解析后的测试将是实现此目的的最简单方法:
A test after parsing would be the simplest way to achieve this:
if args.arg2 and args.arg1 is None:
args.arg1 = 1
您可以将此类测试放在自定义操作中.您必须考虑出现(或不出现)的顺序.我还没有弄清楚细节,但我无法想象它比这个解析后测试更简单.
You could put this sort of test in an custom Action. You have to take into consideration the order of occurance (or not). I haven't worked out the details, but I can't imagine it being any simpler than this post-parse test.
这篇关于是否可以根据其他可选参数将 argparse 的可选参数设置为默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!