Python创建命令行应用的工具 tools for command line application in python

工具1:Docopt

地址:http://docopt.org/

这个工具是根据模块的文档注释来确定参数的。注释分为两部分:Usage, option。

\```
Usage:
  naval_fate ship new <name>...
  naval_fate ship <name> move <x> <y> [--speed=<kn>]
  naval_fate ship shoot <x> <y>
  naval_fate mine (set|remove) <x> <y> [--moored|--drifting]
  naval_fate -h | --help
  naval_fate --version

Options:
  -h --help     Show this screen.
  --version     Show version.
  --speed=<kn>  Speed in knots [default: 10].
  --moored      Moored (anchored) mine.
  --drifting    Drifting mine.
\```

指定了这些参数,就可以在程序中调用相关参数,使用get方法。

arguments = docopt(__doc__, version=myapp 1.0')
if arguments.get("add"):
    print("添加成功")
elif arguments.get("delete"):
    print("删除成功")

工具2:click

https://click.palletsprojects.com/en/7.x/

click是使用装饰器,根据这些来自动生成帮助文件。

import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()

这样,帮助文件就生成了:

$ python hello.py --help
Usage: hello.py [OPTIONS]

  Simple program that greets NAME for a total of COUNT times.

Options:
  --count INTEGER  Number of greetings.
  --name TEXT      The person to greet.
  --help           Show this message and exit.
posted @ 2019-04-22 16:04  何大卫  阅读(428)  评论(0编辑  收藏  举报