How to parse multiple nested sub-commands using python argparse?

后端 未结 11 1058
执念已碎
执念已碎 2020-11-28 20:52

I am implementing a command line program which has interface like this:

cmd [GLOBAL_OPTIONS] {command [COMMAND_OPTS]} [{command [COMMAND_OPTS]} ...]
<         


        
11条回答
  •  有刺的猬
    2020-11-28 21:42

    Another package which supports parallel parsers is "declarative_parser".

    import argparse
    from declarative_parser import Parser, Argument
    
    supported_formats = ['png', 'jpeg', 'gif']
    
    class InputParser(Parser):
        path = Argument(type=argparse.FileType('rb'), optional=False)
        format = Argument(default='png', choices=supported_formats)
    
    class OutputParser(Parser):
        format = Argument(default='jpeg', choices=supported_formats)
    
    class ImageConverter(Parser):
        description = 'This app converts images'
    
        verbose = Argument(action='store_true')
        input = InputParser()
        output = OutputParser()
    
    parser = ImageConverter()
    
    commands = '--verbose input image.jpeg --format jpeg output --format gif'.split()
    
    namespace = parser.parse_args(commands)
    

    and namespace becomes:

    Namespace(
        input=Namespace(format='jpeg', path=<_io.BufferedReader name='image.jpeg'>),
        output=Namespace(format='gif'),
        verbose=True
    )
    

    Disclaimer: I am the author. Requires Python 3.6. To install use:

    pip3 install declarative_parser
    

    Here is the documentation and here is the repo on GitHub.

提交回复
热议问题