问题
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)
Is there a way to set arg1
default value of "1" if only if arg2
is set 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)
Otherwise, it will be set to:
parser.add_argument('-a', '--arg1', type=int)
回答1:
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.
来源:https://stackoverflow.com/questions/30337602/is-it-possible-to-set-argparses-optional-argument-to-a-default-value-based-on-o