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’])
发布了213 篇原创文章 · 获赞 7 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/chuckchen1222/article/details/102978387