찾다
백엔드 개발파이썬 튜토리얼Introspection, 클릭 및 다양한 형식을 사용하여 Python CLI용 대화형 채팅을 구축하는 방법

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

CLI를 더욱 대화형이고 동적으로 만들고 싶다면 실시간 명령 상호 작용 시스템을 구축하는 것이 답이 될 수 있습니다. Python의 내부 검사 기능, 명령 관리를 위한 Click, 출력 형식 지정을 위한 Rich를 활용하여 사용자 입력에 지능적으로 응답하는 강력하고 유연한 CLI를 만들 수 있습니다. 각 명령을 수동으로 하드코딩하는 대신 CLI가 자동으로 명령을 검색하고 실행할 수 있으므로 사용자 경험이 더욱 원활하고 매력적으로 만들어집니다.

다채로운 콘솔 혼돈: 클릭 명령과 풍부한 출력이 만나는 곳 — 터미널도 스타일을 과시하기를 좋아하기 때문입니다!

클릭과 마크다운을 사용하는 이유는 무엇입니까?

클릭은 명령 관리, 인수 구문 분석 및 도움말 생성을 단순화합니다. 또한 명령 구조화 및 옵션 처리가 쉽습니다.

Rich를 사용하면 아름다운 형식의 Markdown을 터미널에서 직접 출력할 수 있어 기능적일 뿐만 아니라 시각적으로도 매력적인 결과를 얻을 수 있습니다.

이 두 라이브러리를 Python 내부 검사와 결합하면 출력을 풍부하고 읽기 쉬운 형식으로 표시하는 동시에 명령을 동적으로 검색하고 실행하는 대화형 채팅 기능을 구축할 수 있습니다. 실용적인 예를 보려면 StoryCraftr이 유사한 접근 방식을 사용하여 AI 기반 글쓰기 작업 흐름을 간소화하는 방법을 확인하세요. https://storycraftr.app.

대화형 채팅 시스템 구축

1. 기본 채팅 명령어 설정하기

채팅 명령은 세션을 초기화하여 사용자가 CLI와 상호 작용할 수 있도록 합니다. 여기서는 적절한 클릭 명령에 동적으로 매핑되는 사용자 입력을 캡처합니다.

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의 데코레이터를 처리하는 방법은 다음과 같습니다.

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, Markdown 서식 지정을 위한 Rich, Python 자체 검사를 결합하여 CLI를 위한 강력하고 대화형 채팅 시스템을 구축할 수 있습니다. 이 접근 방식을 사용하면 우아하고 읽기 쉬운 형식으로 출력을 표시하면서 명령을 동적으로 검색하고 실행할 수 있습니다.

주요 하이라이트:

  • 동적 명령 실행: Introspection을 사용하면 명령을 하드코딩하지 않고도 검색하고 실행할 수 있습니다.
  • 리치 출력: 리치 마크다운을 사용하면 출력이 읽기 쉽고 시각적으로 매력적입니다.
  • 유연성: 이 설정은 명령 구조와 실행에 유연성을 제공합니다.

위 내용은 Introspection, 클릭 및 다양한 형식을 사용하여 Python CLI용 대화형 채팅을 구축하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Python의 하이브리드 접근법 : 컴파일 및 해석 결합Python의 하이브리드 접근법 : 컴파일 및 해석 결합May 08, 2025 am 12:16 AM

PythonuseSahybrideactroach, combingingcompytobytecodeandingretation.1) codeiscompiledToplatform-IndependentBecode.2) bytecodeistredbythepythonvirtonmachine, enterancingefficiency andportability.

Python 's 'for'와 'whind'루프의 차이점을 배우십시오Python 's 'for'와 'whind'루프의 차이점을 배우십시오May 08, 2025 am 12:11 AM

"for"and "while"loopsare : 1) "에 대한"loopsareIdealforitertatingOverSorkNowniterations, whide2) "weekepindiTeRations.Un

Python Concatenate는 중복과 함께 목록입니다Python Concatenate는 중복과 함께 목록입니다May 08, 2025 am 12:09 AM

Python에서는 다양한 방법을 통해 목록을 연결하고 중복 요소를 관리 할 수 ​​있습니다. 1) 연산자를 사용하거나 ()을 사용하여 모든 중복 요소를 유지합니다. 2) 세트로 변환 한 다음 모든 중복 요소를 제거하기 위해 목록으로 돌아가지 만 원래 순서는 손실됩니다. 3) 루프 또는 목록 이해를 사용하여 세트를 결합하여 중복 요소를 제거하고 원래 순서를 유지하십시오.

파이썬 목록 연결 성능 ​​: 속도 비교파이썬 목록 연결 성능 ​​: 속도 비교May 08, 2025 am 12:09 AM

fastestestestedforListCancatenationInpythondSpendsonListsize : 1) Forsmalllist, OperatoriseFficient.2) ForlargerLists, list.extend () OrlistComprehensionIsfaster, withextend () morememory-efficientBymodingListsin-splace.

Python 목록에 요소를 어떻게 삽입합니까?Python 목록에 요소를 어떻게 삽입합니까?May 08, 2025 am 12:07 AM

toInsertElmentsIntoapyThonList, useAppend () toaddtotheend, insert () foraspecificposition, andextend () andextend () formultipleElements.1) useappend () foraddingsingleitemstotheend.2) useinsert () toaddatespecificindex, 그러나)

Python은 후드 아래에 동적 배열 또는 링크 된 목록이 있습니까?Python은 후드 아래에 동적 배열 또는 링크 된 목록이 있습니까?May 07, 2025 am 12:16 AM

pythonlistsareimplementedesdynamicarrays, notlinkedlists.1) thearestoredIntIguousUousUousUousUousUousUousUousUousUousInSeripendExeDaccess, LeadingSpyTHOCESS, ImpactingEperformance

파이썬 목록에서 요소를 어떻게 제거합니까?파이썬 목록에서 요소를 어떻게 제거합니까?May 07, 2025 am 12:15 AM

PythonoffersfourmainmethodstoremoveElementsfromalist : 1) 제거 (값) 제거 (값) removesthefirstoccurrencefavalue, 2) pop (index) 제거 elementatAspecifiedIndex, 3) delstatemeveselementsByindexorSlice, 4) RemovesAllestemsfromTheChmetho

스크립트를 실행하려고 할 때 '허가 거부'오류가 발생하면 무엇을 확인해야합니까?스크립트를 실행하려고 할 때 '허가 거부'오류가 발생하면 무엇을 확인해야합니까?May 07, 2025 am 12:12 AM

Toresolvea "permissionDenied"오류가 발생할 때 오류가 발생합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

mPDF

mPDF

mPDF는 UTF-8로 인코딩된 HTML에서 PDF 파일을 생성할 수 있는 PHP 라이브러리입니다. 원저자인 Ian Back은 자신의 웹 사이트에서 "즉시" PDF 파일을 출력하고 다양한 언어를 처리하기 위해 mPDF를 작성했습니다. HTML2FPDF와 같은 원본 스크립트보다 유니코드 글꼴을 사용할 때 속도가 느리고 더 큰 파일을 생성하지만 CSS 스타일 등을 지원하고 많은 개선 사항이 있습니다. RTL(아랍어, 히브리어), CJK(중국어, 일본어, 한국어)를 포함한 거의 모든 언어를 지원합니다. 중첩된 블록 수준 요소(예: P, DIV)를 지원합니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.