Python dependencies between groups using argparse

前端 未结 3 1684
轻奢々
轻奢々 2021-02-09 13:13

I started to learn Python, and now I\'m learning the great benefits of argparse. Using argparse, I have created two groups of arguments: group_li

3条回答
  •  情话喂你
    2021-02-09 13:47

    Use Docopt! You shouldn't have to write a usage doc and then spend hours trying to figure out how to get argparse to create it for you. If you know POSIX you know how to interpret a usage doc because it is a standard. Docopt know how to interpret usage docs that same as you do. We don't need an abstraction layer.

    I think the OP has failed to describe their own intentions based on what I read in their help text. I'm going to try and speculate what they are trying to do.


    test.py

    """
    usage: test.py [-h | --version]
           test.py [-v] (-m | -p)
           test.py [-v] --list (modules | ports)
           test.py [-v] (-M  | -P  | -I )
    
    this is the description
    
    optional arguments:
      -h, --help                show this help message and exit
      -v, --verbose             verbose
      -m                        list only modules (same as --list modules)
      -p                        list only ports   (same as --list ports)
      --list                    list only module or ports
      -M module_name            simulate module down
      -P fc_port_name           simulate FC port down
      -I iSCSI_port_name        simulate iSCSI port down
    
    This is the epilog
    """
    
    from pprint import pprint
    from docopt import docopt
    
    def cli():
        arguments = docopt(__doc__, version='Super Tool 0.2')
        pprint(arguments)
    
    if __name__ == '__main__':
        cli()
    

    While it would be possible to communicate all of the usage in a single line with complex nested conditionals, this is more legible. This is why docopt makes so much sense. For a CLI program you want to make sure you communicate to the user clearly. Why learn some obscure module syntax in the hope that you can convince it to create the communication to the user for you? Take the time to look at other POSIX tools with option rules similar to your needs and copy-pasta.

提交回复
热议问题