Require either of two arguments using argparse

十年热恋 提交于 2020-01-22 04:09:49

问题


Given:

import argparse

pa = argparse.ArgumentParser()
pa.add_argument('--foo')
pa.add_argument('--bar')

print pa.parse_args('--foo 1'.split())

how do I

  • make at least one of "foo, bar" mandatory: --foo x, --bar y and --foo x --bar y are fine
  • make at most one of "foo, bar" mandatory: --foo x or --bar y are fine, --foo x --bar y is not

回答1:


I think you are searching for something like mutual exclusion (at least for the second part of your question).

This way, only foo or bar will be accepted, not both.

    import argparse

    parser = argparse.ArgumentParser()
    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('--foo',action=.....)
    group.add_argument('--bar',action=.....)
    args = parser.parse_args()

BTW, just found another question referring to the same kind of issue.

Hope this helps




回答2:


If you need some check that is not provided by the module you can always do it manually:

pa = argparse.ArgumentParser()
...
args = pa.parse_args()

if args.foo is None and args.bar is None:
   pa.error("at least one of --foo and --bar required")


来源:https://stackoverflow.com/questions/11154946/require-either-of-two-arguments-using-argparse

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