将Python脚本变为命令行--click模块使用

import click
# click.option 中的命令规则可参考参数名称。它接受的前两个参数为长、短选项(顺序随意),其中:
#
# 长选项以 “--” 开头,比如 “--string-to-echo”
# 短选项以 “-” 开头,比如 “-s”



@click.group()
def main():
    pass


@main.command()
@click.option('-u', '--user_name', type=str, help='add user_name')
def get_user(user_name):
    click.echo(f'search user:{user_name}')


@main.command()
@click.option('-u', '--user_name', required=True, type=str, help="要添加的用户名")
@click.option('-p', '--password', required=True, type=str, help="要添加的密码")
@click.option('-t', '--id_type', required=True, default="phone", type=str, help="添加的账户类型",show_default=True)
def add_user(user_name, password, id_type):
    click.echo(f"{user_name=}  {password=} {id_type=}")



if __name__ == '__main__':
    main()

使用方式

python3 demo.py get-user -u "122"

或者

python3 demo.py add-user -u "123" -p "12"  
原文地址:https://www.cnblogs.com/c-x-a/p/9767103.html