1. import click
    2. @click.command()
    3. @click.option('--count', default=1, help='Number of greetings.')
    4. @click.option('--name', prompt='Your name', help='The person to greet.')
    5. def hello(count, name):
    6. """Simple program that greets NAME for a total of COUNT times."""
    7. for x in range(count):
    8. click.echo('Hello %s!' % name)
    9. if __name__ == '__main__':
    10. hello()
    1. python click_hello.py --count=3
    2. Your name: kyle
    3. Hello kyle!
    4. Hello kyle!
    5. Hello kyle!
    6. python click_hello.py --help
    7. Usage: click_hello.py [OPTIONS]
    8. Simple program that greets NAME for a total of COUNT times.
    9. Options:
    10. --count INTEGER Number of greetings.
    11. --name TEXT The person to greet.
    12. --help Show this message and exit.

    prompt 为 true,交互式输入密码
    hide_input 为 True,可以隐藏命令行输入
    confirmation_prompt 为True,密码二次验证

    1. import click
    2. @click.command()
    3. @click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True)
    4. def encrypt(password):
    5. click.echo('Encrypting password to %s' % password.encode('rot13'))
    6. if __name__ == '__main__':
    7. encrypt()
    1. from prompt_toolkit import prompt
    2. while True:
    3. user_input = prompt('>')
    4. print(user_input)

    历史命令输入支持

    1. from prompt_toolkit import prompt
    2. from prompt_toolkit.history import FileHistory
    3. while True:
    4. user_input = prompt('>', history=FileHistory('history.txt'))
    5. print(user_input)
    1. cat history.txt
    2. # 2021-03-11 12:06:56.871280
    3. +dfsgsg
    4. # 2021-03-11 12:06:58.126798
    5. +sldbfnvljdfs
    6. # 2021-03-11 12:06:59.568565
    7. +avriuiue
    8. # 2021-03-11 12:07:00.651740
    9. +aoinsbnv

    用户输入时自动提示

    1. from prompt_toolkit import prompt
    2. from prompt_toolkit.history import FileHistory
    3. from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
    4. while True:
    5. user_input = prompt('>', history=FileHistory(
    6. 'history.txt'), auto_suggest=AutoSuggestFromHistory())
    7. print(user_input)

    自动补全

    1. from prompt_toolkit import prompt
    2. from prompt_toolkit.history import FileHistory
    3. from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
    4. from prompt_toolkit.completion import WordCompleter
    5. SQLCompleter = WordCompleter(
    6. ['select', 'from', 'insert', 'update', 'delete', 'drop'], ignore_case=True)
    7. while True:
    8. user_input = prompt('>', history=FileHistory(
    9. 'history.txt'), auto_suggest=AutoSuggestFromHistory(), completer=SQLCompleter)
    10. print(user_input)