Argparse: Required arguments listed under “optional arguments”?

后端 未结 4 466
暗喜
暗喜 2020-12-12 09:02

I use the following simple code to parse some arguments; note that one of them is required. Unfortunately, when the user runs the script without providing the argument, the

4条回答
  •  悲&欢浪女
    2020-12-12 09:11

    Building off of @Karl Rosaen

    parser = argparse.ArgumentParser()
    optional = parser._action_groups.pop() # Edited this line
    required = parser.add_argument_group('required arguments')
    # remove this line: optional = parser...
    required.add_argument('--required_arg', required=True)
    optional.add_argument('--optional_arg')
    parser._action_groups.append(optional) # added this line
    return parser.parse_args()
    

    and this outputs:

    usage: main.py [-h] [--required_arg REQUIRED_ARG]
               [--optional_arg OPTIONAL_ARG]
    
    required arguments:
      --required_arg REQUIRED_ARG
    
    optional arguments:
      -h, --help                    show this help message and exit
      --optional_arg OPTIONAL_ARG
    

提交回复
热议问题