搜尋
首頁後端開發Python教學如何使用內省、點擊和豐富格式為 Python CLI 建立互動式聊天

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中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
python中兩個列表的串聯替代方案是什麼?python中兩個列表的串聯替代方案是什麼?May 09, 2025 am 12:16 AM

可以使用多種方法在Python中連接兩個列表:1.使用 操作符,簡單但在大列表中效率低;2.使用extend方法,效率高但會修改原列表;3.使用 =操作符,兼具效率和可讀性;4.使用itertools.chain函數,內存效率高但需額外導入;5.使用列表解析,優雅但可能過於復雜。選擇方法應根據代碼上下文和需求。

Python:合併兩個列表的有效方法Python:合併兩個列表的有效方法May 09, 2025 am 12:15 AM

有多種方法可以合併Python列表:1.使用 操作符,簡單但對大列表不內存高效;2.使用extend方法,內存高效但會修改原列表;3.使用itertools.chain,適用於大數據集;4.使用*操作符,一行代碼合併小到中型列表;5.使用numpy.concatenate,適用於大數據集和性能要求高的場景;6.使用append方法,適用於小列表但效率低。選擇方法時需考慮列表大小和應用場景。

編譯的與解釋的語言:優點和缺點編譯的與解釋的語言:優點和缺點May 09, 2025 am 12:06 AM

CompiledLanguagesOffersPeedAndSecurity,而interneterpretledlanguages provideeaseafuseanDoctability.1)commiledlanguageslikec arefasterandSecureButhOnderDevevelmendeclementCyclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesclesandentency.2)cransportedeplatectentysenty

Python:對於循環,最完整的指南Python:對於循環,最完整的指南May 09, 2025 am 12:05 AM

Python中,for循環用於遍歷可迭代對象,while循環用於條件滿足時重複執行操作。 1)for循環示例:遍歷列表並打印元素。 2)while循環示例:猜數字遊戲,直到猜對為止。掌握循環原理和優化技巧可提高代碼效率和可靠性。

python concatenate列表到一個字符串中python concatenate列表到一個字符串中May 09, 2025 am 12:02 AM

要將列表連接成字符串,Python中使用join()方法是最佳選擇。 1)使用join()方法將列表元素連接成字符串,如''.join(my_list)。 2)對於包含數字的列表,先用map(str,numbers)轉換為字符串再連接。 3)可以使用生成器表達式進行複雜格式化,如','.join(f'({fruit})'forfruitinfruits)。 4)處理混合數據類型時,使用map(str,mixed_list)確保所有元素可轉換為字符串。 5)對於大型列表,使用''.join(large_li

Python的混合方法:編譯和解釋合併Python的混合方法:編譯和解釋合併May 08, 2025 am 12:16 AM

pythonuseshybridapprace,ComminingCompilationTobyTecoDeAndInterpretation.1)codeiscompiledtoplatform-Indepententbybytecode.2)bytecodeisisterpretedbybythepbybythepythonvirtualmachine,增強效率和通用性。

了解python的' for”和' then”循環之間的差異了解python的' for”和' then”循環之間的差異May 08, 2025 am 12:11 AM

theKeyDifferencesBetnewpython's“ for”和“ for”和“ loopsare:1)” for“ loopsareIdealForiteringSequenceSquencesSorkNowniterations,而2)”,而“ loopsareBetterforConterContinuingUntilacTientInditionIntionismetismetistismetistwithOutpredefinedInedIterations.un

Python串聯列表與重複Python串聯列表與重複May 08, 2025 am 12:09 AM

在Python中,可以通過多種方法連接列表並管理重複元素:1)使用 運算符或extend()方法可以保留所有重複元素;2)轉換為集合再轉回列表可以去除所有重複元素,但會丟失原有順序;3)使用循環或列表推導式結合集合可以去除重複元素並保持原有順序。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。