python - 如何使用 python-click 构建类似 kubectl 的 CLI?
问题描述
我想创建一个 CLI,以某种kubectl
方式接收操作和资源参数以工作。例如。
myctl init config
myctl create issue|pr|branch
myctl delete issue|pr|branch|config
myctl 命令应该总是接收 2 个参数,这样用户就不会尝试类似:myctl init config delete issue
. 也不应该能够执行不可能的组合,例如myctl create config
.
我虽然有一些代码,例如:
import click
@click.command()
@click.group()
@click.option(
"init,create,delete",
type=str,
help="Action name.",
)
@click.option(
"config,issue,pr,branch",
type=str,
help="Resource name.",
)
def main(action: str, resource: str) -> None:
pass
if __name__ == "__main__":
main(prog_name="myctl")
我不确定我应该使用哪些点击元素来构建它(参数、选项、组等)以及如何将它们组合在一起。
解决方案
我过去通过创建多个嵌套组实现了这一点。
import click
@click.group('cli')
def cli():
pass
@click.group('init')
def init():
pass
@click.group('create')
def create():
pass
@click.group('delete')
def delete():
pass
@init.command('config')
def config():
print('Configuration complete')
@create.command('issue')
@click.argument('name')
def issue(name):
print(f'Created {name}')
@create.command('pr')
@click.argument('base_branch', required=False, default='master')
def pr(base_branch):
print(f'Created PR against {base_branch}')
@create.command('branch')
@click.argument('name')
def branch(name):
print(f'Create branch {name}')
@delete.command('issue')
@click.argument('issue_number')
def delete_issue(issue_number):
print(f'Deleting issue {issue_number}')
@delete.command('pr')
@click.argument('pr_number')
def delete_pr(pr_number):
print(f'Deleting PR {pr_number}')
@delete.command('branch')
@click.argument('branch_name')
def delete_branch(branch_name):
print(f'Deleting branch {branch_name}')
@delete.command('config')
@click.argument('config_name')
def delete_config(config_name):
print(f'Deleting config {config_name}')
cli.add_command(init)
cli.add_command(create)
cli.add_command(delete)
def run_cli():
cli()
if __name__ == "__main__":
run_cli()
然后,您可以根据需要扩展它,调用如下所示。我已经调用了我的 CLI play
。
❯ play
Usage: play [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
create
delete
init
❯ play init
Usage: play init [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
config
❯ play init config
Configuration complete
❯ play create
Usage: play create [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
branch
issue
pr
❯ play create branch feature/the-coolest
Create branch feature/the-coolest
然后,您可以继续添加简短的帮助消息并将其自定义到您的应用程序。
推荐阅读
- javascript - 如何默认显示工具提示而不在纯css中悬停
- excel - VBA - 创建字符串/哈希的唯一ID
- javascript - 表单动作不会被“必需的”输入打断
- node.js - TypeORM & PM2:无法在 Heroku 上运行应用程序
- javascript - Firestore orderBy timestamp desc 不起作用
- animation - 在 React Native 中通过用户触摸旋转光盘
- mongoose - 找不到模块“/Users/mymacbook/install”
- javascript - 使用 office.js 和加载项替换 PowerPoint 中的特定文本
- powershell - 无法使用 Powercli 检索“EsxCli”的“software.acceptance”值
- reactjs - 通过不同的id调用多个值