Python Argparse conditionally required arguments

后端 未结 6 559
梦谈多话
梦谈多话 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:31

    For arguments I've come up with a quick-n-dirty solution like this. Assumptions: (1) '--help' should display help and not complain about required argument and (2) we're parsing sys.argv

    p = argparse.ArgumentParser(...)
    p.add_argument('-required', ..., required = '--help' not in sys.argv )
    

    This can easily be modified to match a specific setting. For required positionals (which will become unrequired if e.g. '--help' is given on the command line) I've come up with the following: [positionals do not allow for a required=... keyword arg!]

    p.add_argument('pattern', ..., narg = '+' if '--help' not in sys.argv else '*' )
    

    basically this turns the number of required occurrences of 'pattern' on the command line from one-or-more into zero-or-more in case '--help' is specified.

提交回复
热议问题