是否可以基于其他可选参数将argparse的可选参数设置为默认值? [英] Is it possible to set argparse's optional argument to a default value based on other optional argument?

查看:266
本文介绍了是否可以基于其他可选参数将argparse的可选参数设置为默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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屋!

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