1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/149045/1600742078923-a901915d-8587-4def-a2be-3bf67ec65feb.png#align=left&display=inline&height=100&margin=%5Bobject%20Object%5D&name=image.png&originHeight=199&originWidth=503&size=11401&status=done&style=shadow&width=252)

https://click.palletsprojects.com/

basic

  1. # test.py
  2. import click
  3. @click.command()
  4. @click.option('--count', default=1, help='Number of greetings.')
  5. @click.option('--name', prompt='Your name', help='The person to greet.')
  6. def hello(count, name):
  7. """Simple program that greets NAME for a total of COUNT times."""
  8. for x in range(count):
  9. click.echo('Hello %s!' % name)
  10. if __name__ == '__main__':
  11. hello()

image.png

group+pass_context

  1. import click
  2. @click.group()
  3. @click.pass_context
  4. @click.option('--url', help='the url of wiki api', default=DEFAULT_URL)
  5. @click.option('-u', '--username', help='the username to login', default='suqingdong')
  6. @click.option('-p', '--password', help='the password to login', hide_input=True, prompt=True)
  7. def cli(ctx, url, username, password):
  8. ctx.ensure_object(dict)
  9. api = WikiAPI(url, username, password)
  10. ctx.obj['api'] = api
  11. @cli.command()
  12. @click.pass_context
  13. @click.argument('filepath')
  14. @click.option('-n', '--name', help='the name of file')
  15. def upload(ctx, filepath, name):
  16. api = ctx.obj['api']
  17. api.upload(filepath, name)
  18. @cli.command()
  19. @click.pass_context
  20. @click.argument('filepath')
  21. def import_xml(ctx, filepath):
  22. api = ctx.obj['api']
  23. api.import_xml(filepath)
  24. if __name__ == '__main__':
  25. cli(obj={})

一些配置

-h帮助, 默认显示帮助

  1. CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
  2. @click.command(no_args_is_help=True, context_settings=CONTEXT_SETTINGS)