
如果您曾经想让您的 cli 更具交互性和动态性,构建实时命令交互系统可能是答案。通过利用 python 的自省功能、用于管理命令的 click 以及用于格式化输出的 rich,您可以创建一个强大、灵活的 cli,以智能地响应用户输入。您的 cli 可以自动发现并执行命令,而不是手动硬编码每个命令,从而使用户体验更流畅、更具吸引力。
丰富多彩的控制台混乱:点击命令与丰富的输出相遇 - 因为即使是终端也喜欢炫耀风格!
click 简化了命令管理、参数解析和帮助生成。它还允许轻松的命令结构和选项处理。
rich 使您能够直接在终端中输出格式精美的 markdown,使结果不仅实用,而且具有视觉吸引力。
通过将这两个库与 python 自省相结合,您可以构建交互式聊天功能,该功能可以动态发现和执行命令,同时以丰富、可读的格式显示输出。 有关实际示例,请了解 storycraftr 如何使用类似的方法来简化 ai 驱动的写作工作流程: https://storycraftr.app。
聊天命令初始化会话,允许用户与 cli 交互。在这里,我们捕获用户输入,这些输入将动态映射到适当的 click 命令。
import os
import click
import shlex
from rich.console import console
from rich.markdown import markdown
console = console()
@click.command()
@click.option("--project-path", type=click.path(), help="path to the project directory")
def chat(project_path=none):
"""
start a chat session with the assistant for the given project.
"""
if not project_path:
project_path = os.getcwd()
console.print(
f"starting chat for [bold]{project_path}[/bold]. type [bold green]exit()[/bold green] to quit."
)
# start the interactive session
while true:
user_input = console.input("[bold blue]you:[/bold blue] ")
# handle exit
if user_input.lower() == "exit()":
console.print("[bold red]exiting chat...[/bold red]")
break
# call the function to handle command execution
execute_cli_command(user_input)
使用python内省,我们动态地发现可用的命令并执行它们。这里的一个关键部分是 click 命令是修饰函数。为了执行实际的逻辑,我们需要调用未修饰的函数(即回调)。
立即学习“Python免费学习笔记(深入)”;
以下是如何使用内省动态执行命令并处理 click 的装饰器:
import inspect
import your_project_cmd # replace with your actual module containing commands
command_modules = {"project": your_project_cmd} # list your command modules here
def execute_cli_command(user_input):
"""
function to execute cli commands dynamically based on the available modules,
calling the undecorated function directly.
"""
try:
# use shlex.split to handle quotes and separate arguments correctly
parts = shlex.split(user_input)
module_name = parts[0]
command_name = parts[1].replace("-", "_") # replace hyphens with underscores
command_args = parts[2:] # keep the rest of the arguments as a list
# check if the module exists in command_modules
if module_name in command_modules:
module = command_modules[module_name]
# introspection: get the function by name
if hasattr(module, command_name):
cmd_func = getattr(module, command_name)
# check if it's a click command and strip the decorator
if hasattr(cmd_func, "callback"):
# call the underlying undecorated function
cmd_func = cmd_func.callback
# check if it's a callable (function)
if callable(cmd_func):
console.print(
f"executing command from module: [bold]{module_name}[/bold]"
)
# directly call the function with the argument list
cmd_func(*command_args)
else:
console.print(
f"[bold red]'{command_name}' is not a valid command[/bold red]"
)
else:
console.print(
f"[bold red]command '{command_name}' not found in {module_name}[/bold red]"
)
else:
console.print(f"[bold red]module {module_name} not found[/bold red]")
except exception as e:
console.print(f"[bold red]error executing command: {str(e)}[/bold red]")
让我们考虑项目模块中的一些示例命令,用户可以通过聊天交互调用这些命令:
@click.group()
def project():
"""project management cli."""
pass
@project.command()
def init():
"""initialize a new project."""
console.print("[bold green]project initialized![/bold green]")
@project.command()
@click.argument("name")
def create(name):
"""create a new component in the project."""
console.print(f"[bold cyan]component {name} created.[/bold cyan]")
@project.command()
def status():
"""check the project status."""
console.print("[bold yellow]all systems operational.[/bold yellow]")
运行交互式聊天系统:
python your_cli.py chat --project-path /path/to/project
会话开始后,用户可以输入以下命令:
you: project init you: project create "homepage"
输出将使用 rich markdown 以格式良好的方式显示:
[bold green]Project initialized![/bold green] [bold cyan]Component Homepage created.[/bold cyan]
通过结合 click 命令管理、rich for markdown 格式和 python 自省,我们可以为 cli 构建一个强大的交互式聊天系统。这种方法允许您动态发现和执行命令,同时以优雅、可读的格式呈现输出。
主要亮点:
以上就是如何使用内省、单击和丰富格式为 Python CLI 构建交互式聊天的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号