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

前端 未结 4 610
醉话见心
醉话见心 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:11

    Just stumbled on this problem myself. From my reading of the argparse docs, there doesn't seem to be a simple way to achieve that within argparse. I considered using parse_known_args, but that soon amounts to writing a special-purpose version of argparse ;-)

    Perhaps a bug report is in order. In the meanwhile, if you're willing to make your user do a tiny bit extra typing, you can fake it with subgroups (like how git and svn's arguments work), e.g.

        subparsers = parser.add_subparsers()
        p_ab = subparsers.add_parser('ab')
        p_ab.add_argument(...)
    
        p_cd = subparsers.add_parser('cd')
        p_cd.add_argument(...)
    

    Not ideal, but at least it gives you the good from argparse without too much ugly hackery. I ended up doing away with the switches and just using the subparser operations with required subarguments.

提交回复
热议问题