python - click - 命令行交互

click包,非常簡單的命令行交互的包。
Click is a simple Python module inspired by the stdlib optparse to make writing command line scripts fun. Unlike other modules, it’s based around a simple API that does not come with too much magic and is composable.

簡單使用:

import click
@click.command()
@click.option('-a','--aa',default='a',help='This is a')
@click.option('-c','--cc',prompt="C", help='This is c.')
@click.argument('b')
def func(aa,b,cc):
    print ("Func, para is %s, argument is %s, prompt c is %s" % (aa,b,cc))
func()

執行:

# python test_08_01.py --help
Usage: test_08_01.py [OPTIONS] B

Options:
  -a, --aa TEXT  This is a
  -c, --cc TEXT  This is c.
  --help         Show this message and exit.

# python test_08_01.py bb --aa=aaa
C: ccc
Func, para is aaa, argument is bb, prompt c is ccc

使用2,多功能執行:

import click

@click.group()
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True)
@click.option('--name')
def cli(name,password):
    print ("name is %s, password is %s!" % (name, password))

@cli.command()
@click.option('--message', '-m', multiple=True, help='you can input multi messages.')
def send_mes(message):
    print ("This is func send_mes. message is %s" % '\n'.join(message))


@cli.command()
@click.option('--func1','-f1', help='This is Function 1.')
def execute_func1(func1):
    print ("Function 1 is being executed. %s " % func1)

@cli.command()
@click.option('--func2','-f2', help='This is Function 2.')
def execute_func2(func2):
    print ("Function 2 is being executed. %s " % func2)

@cli.command()
@click.option('--type', '-t', type=click.Choice(['x', 'y']), help='Choic x or y')
def select_type(type):
    print ('Your choice is %s' % type)

cli()

執行:

# python test_08_01.py
Usage: test_08_01.py [OPTIONS] COMMAND [ARGS]...
Options:
  --password TEXT
  --name TEXT
  --help           Show this message and exit.
Commands:
  execute-func1
  execute-func2
  select-type
  send-mes

# python test_08_01.py --name=zc execute-func1 --func1=abc
Password:
Repeat for confirmation:
name is zc, password is 123456!
Function 1 is being executed. abc

# python test_08_01.py --name=zc send-mes -m a -m b -m c
Password:
Repeat for confirmation:
name is zc, password is 1!
This is func send_mes. message is a
b
c

# python test_08_01.py --name=zc select-type --type=x
Password:
Repeat for confirmation:
name is zc, password is 1!
Your choice is x

總結:

  1. 需要多個功能時,先建一個主的組,然後其他函數使用主函數組的command即可
  2. 隱藏密碼參數可以使用hide_input=True,
  3. 使用命令行輸入參數使用prompt=True,使用confirmation_prompt=True表示是否需要第二遍輸入,一般配合密碼使用。
  4. 選擇參數用 click.Choice([‘x’, ‘y’])
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章