Python Argparse conditionally required arguments

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

    I've been searching for a simple answer to this kind of question for some time. All you need to do is check if '--argument' is in sys.argv, so basically for your code sample you could just do:

    import argparse
    import sys
    
    if __name__ == '__main__':
        p = argparse.ArgumentParser(description='...')
        p.add_argument('--argument', required=False)
        p.add_argument('-a', required='--argument' in sys.argv) #only required if --argument is given
        p.add_argument('-b', required='--argument' in sys.argv) #only required if --argument is given
        args = p.parse_args()
    

    This way required receives either True or False depending on whether the user as used --argument. Already tested it, seems to work and guarantees that -a and -b have an independent behavior between each other.

提交回复
热议问题