Require either of two arguments using argparse

后端 未结 2 1834
时光说笑
时光说笑 2021-01-29 22:43

Given:

import argparse

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

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

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-29 23:17

    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

提交回复
热议问题