Python argparse : How can I get Namespace objects for argument groups separately?

后端 未结 3 1359
一个人的身影
一个人的身影 2021-01-04 03:36

I have some command line arguments categorized in groups as follows:

cmdParser = argparse.ArgumentParser()
cmdParser.add_argument(\'mainArg\')

groupOne = cm         


        
3条回答
  •  时光说笑
    2021-01-04 03:56

    I was looking for a solution for this for a very long time,
    And I think I finally got it.
    So I will just put it here...

    from argparse import ArgumentParser
    
    def _parse_args():
        parser = ArgumentParser()
        parser.add_argument('-1', '--flag-1', action='store_true', default=False)
        parser.add_argument('-2', '--flag-2', action='store_true', default=False)
        parser.add_argument('-3', '--flag-3', action='store_true', default=False)
    
        args, unknown = parser.parse_known_args()
        print(f"args        : {args}")
        print(f"unknown     : {unknown}")
    
        hidden = ArgumentParser(add_help=False)
        hidden.add_argument('-d', '--debug', action='store_true', default=False)
        hidden_args = hidden.parse_args(unknown)
        print(f"hidden_args : {hidden_args}")
    
    if __name__ == "__main__":
        _parse_args()
    

    as a result:
    show help:

    ubuntu → playAround $ ./test.py -h
    usage: test.py [-h] [-1] [-2] [-3]
    
    optional arguments:
      -h, --help    show this help message and exit
      -1, --flag-1
      -2, --flag-2
      -3, --flag-3
    

    With debug flag:

    ubuntu → playAround $ ./test.py -d
    args        : Namespace(flag_1=False, flag_2=False, flag_3=False)
    unknown     : ['-d']
    hidden_args : Namespace(debug=True)
    

    with flags 1 and 2:

    ubuntu → playAround $ ./test.py -12
    args        : Namespace(flag_1=True, flag_2=True, flag_3=False)
    unknown     : []
    hidden_args : Namespace(debug=False)
    

    with flags 1 and 2 and debug:

    ubuntu → playAround $ ./test.py -12 -d
    args        : Namespace(flag_1=True, flag_2=True, flag_3=False)
    unknown     : ['-d']
    hidden_args : Namespace(debug=True)
    

    The only thing you can't do with this approch is to pass the debug short flag along side to the other short flags:

    ubuntu → playAround $ ./test.py -12d
    usage: test.py [-h] [-1] [-2] [-3]
    test.py: error: argument -2/--flag-2: ignored explicit argument 'd'
    

提交回复
热议问题