Is it possible to set argparse's optional argument to a default value based on other optional argument?

被刻印的时光 ゝ 提交于 2019-12-11 09:45:14

问题


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

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