Does argparse (python) support mutually exclusive groups of arguments?

前端 未结 4 609
醉话见心
醉话见心 2020-12-09 16:55

If I have the arguments \'-a\', \'-b\', \'-c\', \'-d\', with the add_mutually_exclusive_group() function my program will have to use just one of th

4条回答
  •  一整个雨季
    2020-12-09 17:17

    Subparsers?

    Similar to unhammer's answer, but with more user control. Note: I have not actually tested this method, but it should work in theory and with the capabilities of python.

    You can create two parsers, one for each of the two groups, and use conditionals to do the mutually exclusive part. Essentially using argparse for only part of the argument parsing. Using this method, you can go beyond the limitations of unhammer's answer as well.

    # Python 3
    import argparse
    
    try:
        parser = argparse.ArgumentParser()
        parser.add_argument('-a')
        parser.add_argument('-b')
        args = parser.parse_args
    except argparse.ArgumentError:
        parser = argparse.ArgumentParser()
        parser.add_argument('-c')
        parser.add_argument('-d')
        args = parser.parse_args
    

提交回复
热议问题