如何使用内省、单击和丰富格式为 Python CLI 构建交互式聊天
如果您曾经想让您的 CLI 更具交互性和动态性,构建实时命令交互系统可能是答案。通过利用 Python 的自省功能、用于管理命令的 Click 以及用于格式化输出的 Rich,您可以创建一个强大、灵活的 CLI,以智能地响应用户输入。您的 CLI 可以自动发现并执行命令,而不是手动硬编码每个命令,从而使用户体验更流畅、更具吸引力。
丰富多彩的控制台混乱:点击命令与丰富的输出相遇 - 因为即使是终端也喜欢炫耀风格!
为什么使用 Click 和 Markdown?
Click 简化了命令管理、参数解析和帮助生成。它还允许轻松的命令结构和选项处理。
Rich 使您能够直接在终端中输出格式精美的 Markdown,使结果不仅实用,而且具有视觉吸引力。
通过将这两个库与 Python 自省相结合,您可以构建交互式聊天功能,该功能可以动态发现和执行命令,同时以丰富、可读的格式显示输出。 有关实际示例,请了解 StoryCraftr 如何使用类似的方法来简化 AI 驱动的写作工作流程: https://storycraftr.app。
构建互动聊天系统
1. 设置基本聊天命令
聊天命令初始化会话,允许用户与 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)
2. 自省以发现和执行命令
使用Python内省,我们动态地发现可用的命令并执行它们。这里的一个关键部分是 Click 命令是修饰函数。为了执行实际的逻辑,我们需要调用未修饰的函数(即回调)。
以下是如何使用内省动态执行命令并处理 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)
这是如何运作的?
- 输入解析:我们使用 shlex.split 来处理命令行参数等输入。这可确保正确处理带引号的字符串和特殊字符。
- 模块和命令查找:输入分为 module_name 和 command_name。命令名称经过处理,将连字符替换为下划线,以匹配 Python 函数名称。
- 内省:我们使用 getattr() 从模块动态获取命令函数。如果是 Click 命令(即具有回调属性),我们通过剥离 Click 装饰器来访问实际的函数逻辑。
- 命令执行:一旦我们检索到未修饰的函数,我们就传递参数并调用它,就像直接调用 Python 函数一样。
3. CLI 命令示例
让我们考虑项目模块中的一些示例命令,用户可以通过聊天交互调用这些命令:
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]")
执行聊天界面
运行交互式聊天系统:
- 确保您的模块(如项目)已在 command_modules 中列出。
- 运行命令:
@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
输出将使用 Rich Markdown 以格式良好的方式显示:
You: project init You: project create "Homepage"
结论
通过结合 Click 命令管理、Rich for Markdown 格式和 Python 自省,我们可以为 CLI 构建一个强大的交互式聊天系统。这种方法允许您动态发现和执行命令,同时以优雅、可读的格式呈现输出。
主要亮点:
- 动态命令执行:内省使您能够发现和运行命令,而无需对其进行硬编码。
- 丰富的输出:使用 Rich Markdown 可确保输出易于阅读且具有视觉吸引力。
- 灵活性:此设置允许命令结构和执行的灵活性。
以上是如何使用内省、单击和丰富格式为 Python CLI 构建交互式聊天的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Python更易学且易用,C 则更强大但复杂。1.Python语法简洁,适合初学者,动态类型和自动内存管理使其易用,但可能导致运行时错误。2.C 提供低级控制和高级特性,适合高性能应用,但学习门槛高,需手动管理内存和类型安全。

每天学习Python两个小时是否足够?这取决于你的目标和学习方法。1)制定清晰的学习计划,2)选择合适的学习资源和方法,3)动手实践和复习巩固,可以在这段时间内逐步掌握Python的基本知识和高级功能。

Python在开发效率上优于C ,但C 在执行性能上更高。1.Python的简洁语法和丰富库提高开发效率。2.C 的编译型特性和硬件控制提升执行性能。选择时需根据项目需求权衡开发速度与执行效率。

Python和C 各有优势,选择应基于项目需求。1)Python适合快速开发和数据处理,因其简洁语法和动态类型。2)C 适用于高性能和系统编程,因其静态类型和手动内存管理。

pythonlistsarepartofthestAndArdLibrary,herilearRaysarenot.listsarebuilt-In,多功能,和Rused ForStoringCollections,而EasaraySaraySaraySaraysaraySaraySaraysaraySaraysarrayModuleandleandleandlesscommonlyusedDduetolimitedFunctionalityFunctionalityFunctionality。

Python在自动化、脚本编写和任务管理中表现出色。1)自动化:通过标准库如os、shutil实现文件备份。2)脚本编写:使用psutil库监控系统资源。3)任务管理:利用schedule库调度任务。Python的易用性和丰富库支持使其在这些领域中成为首选工具。

Python在科学计算中的应用包括数据分析、机器学习、数值模拟和可视化。1.Numpy提供高效的多维数组和数学函数。2.SciPy扩展Numpy功能,提供优化和线性代数工具。3.Pandas用于数据处理和分析。4.Matplotlib用于生成各种图表和可视化结果。

Python在Web开发中的关键应用包括使用Django和Flask框架、API开发、数据分析与可视化、机器学习与AI、以及性能优化。1.Django和Flask框架:Django适合快速开发复杂应用,Flask适用于小型或高度自定义项目。2.API开发:使用Flask或DjangoRESTFramework构建RESTfulAPI。3.数据分析与可视化:利用Python处理数据并通过Web界面展示。4.机器学习与AI:Python用于构建智能Web应用。5.性能优化:通过异步编程、缓存和代码优
