Python Argparse conditionally required arguments

后端 未结 6 543
梦谈多话
梦谈多话 2020-11-28 09:35

I have done as much research as possible but I haven\'t found the best way to make certain cmdline arguments necessary only under certain conditions, in this case only if ot

6条回答
  •  执念已碎
    2020-11-28 10:19

    This is really the same as @Mira 's answer but I wanted to show it for the case where when an option is given that an extra arg is required:

    For instance, if --option foo is given then some args are also required that are not required if --option bar is given:

    if __name__ == "__main__":
        parser = argparse.ArgumentParser()
        parser.add_argument('--option', required=True,
            help='foo and bar need different args')
    
        if 'foo' in sys.argv:
            parser.add_argument('--foo_opt1', required=True,
               help='--option foo requires "--foo_opt1"')
            parser.add_argument('--foo_opt2', required=True,
               help='--option foo requires "--foo_opt2"')
            ...
    
        if 'bar' in sys.argv:
            parser.add_argument('--bar_opt', required=True,
               help='--option bar requires "--bar_opt"')
            ...
    
    

    It's not perfect - for instance proggy --option foo --foo_opt1 bar is ambiguous but for what I needed to do its ok.

提交回复
热议问题