如何使用內省、點擊和豐富格式為 Python CLI 建立互動式聊天

Barbara Streisand
發布: 2024-10-26 11:00:29
原創
831 人瀏覽過

How to Build an Interactive Chat for Your Python CLI Using Introspection, Click, and Rich Formatting

如果您曾經想讓您的 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]")
登入後複製

執行聊天介面

運行互動式聊天系統:

  1. 確保您的模組(如項目)已在 command_modules 中列出。
  2. 運行指令:
@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中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!