Skip to main content

A modern cmd library based on prompt_toolkit

Project description

ptcmd

License PyPI Build Status PyPI - Downloads Python Version

A modern interactive command-line application building library based on prompt_toolkit

Language: English/中文

Features

  • 🚀 Built on prompt_toolkit, providing powerful interactive experience
  • 📝 Automatic argument parsing and completion
  • 🌈 Rich text output support (using rich library)
  • ⚡ Native async command support
  • 🔍 Built-in command completion and shortcut key support

Installation

Install from PyPI:

pip install ptcmd

Or install from source:

git clone https://github.com/Visecy/ptcmd.git
cd ptcmd
make install

Quick Start

Create a simple command-line application:

import sys
from ptcmd import Cmd

class MyApp(Cmd):
    def do_hello(self, argv: list[str]) -> None:
        """Hello World!"""
        if argv:
            name = argv[0]
        else:
            name = "World"
        self.poutput(f"Hello, {name}!")

if __name__ == "__main__":
    sys.exit(MyApp().cmdloop())

In this simple example:

  1. We created a class MyApp that inherits from Cmd
  2. Defined a command method do_hello for the hello command
  3. The command accepts an optional argument as a name
  4. If no argument is provided, it defaults to "World"
  5. We use the self.poutput() method to output the greeting
  6. Finally, we start the interactive command-line interface with the cmdloop() method

This example demonstrates the most basic usage of ptcmd, including:

  • Command definition method
  • Argument processing
  • Output display
  • Program startup method

After running the program, enter the hello command to experience it:

(Cmd) hello
Hello, World!
(Cmd) hello Alice
Hello, Alice!

Advanced Features

Automatic Argument Parsing

from ptcmd import Cmd, Arg, auto_argument

class MathApp(Cmd):
    @auto_argument
    def do_add(
        self, 
        x: float, 
        y: float,
        *,
        verbose: Arg[bool, "-v", "--verbose"] = False
    ):
        """Add two numbers
        :param x: First number
        :param y: Second number
        :param verbose: Show detailed output
        """
        result = x + y
        if verbose:
            self.poutput(f"{x} + {y} = {result}")
        else:
            self.poutput(result)

Async Command Support

import asyncio
from ptcmd import Cmd, auto_argument

class AsyncApp(Cmd):
    @auto_argument
    async def do_fetch(self, url: str):
        """Fetch URL content"""
        import aiohttp
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                self.poutput(await resp.text())

Library Comparison

Here's a comparison of the strengths and weaknesses of cmd, cmd2, and ptcmd libraries:

Feature cmd (standard lib) cmd2 ptcmd
Feature Richness Basic features Most feature-rich Relatively feature-rich
Learning Curve Simple Medium Medium
Interactive Experience Basic Good Excellent (based on prompt_toolkit)
Auto-completion None Supported Supported
Argument Parsing Manual handling Requires building ArgumentParser Automatic parsing
Async Support None None Native support
Rich Text Output None Uses cmd2.ansi module Uses rich library
Dependencies None Several Most
Performance High Medium Medium
Use Cases Simple interactive CLI Complex interactive CLI Modern interactive CLI

Main advantages:

  • cmd: Python standard library, no extra dependencies, suitable for simple CLI applications
  • cmd2: Comprehensive features, good community support, suitable for traditional CLIs requiring rich functionality
  • ptcmd: Provides the best interactive experience, native async support, suitable for modern CLI applications

Related Projects

  • prompt_toolkit: A Python library for building interactive command-line applications.
  • rich: A Python library for formatting text and output to the terminal.
  • typer: A Python library for building command-line applications.
  • cmd2: A tool for building interactive command-line applications in Python. It aims to make it quick and easy for developers to build feature-rich and user-friendly interactive command-line applications.
  • argparse: Python standard library for parsing command-line arguments and options.
  • cmd: Python standard library for building interactive command-line applications.

Special Thanks

  • cmd2: Provided inspiration for the project, and the command auto-completion logic also references this project.
  • Cline: Helped quickly develop project prototypes and improve documentation and test cases.

License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

ptcmd-0.1.0b1.tar.gz (35.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

ptcmd-0.1.0b1-py3-none-any.whl (30.5 kB view details)

Uploaded Python 3

File details

Details for the file ptcmd-0.1.0b1.tar.gz.

File metadata

  • Download URL: ptcmd-0.1.0b1.tar.gz
  • Upload date:
  • Size: 35.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for ptcmd-0.1.0b1.tar.gz
Algorithm Hash digest
SHA256 0398b39485c0768ce38cff05cb077ffe08cf9f132db502f8c98f770f690dc269
MD5 7f1c21130e51fb16ec1306bc6e6f3407
BLAKE2b-256 8100920f085f1d278825cfd7e9f7f041c39ecfc6e9451ce95bb6d2df139f7129

See more details on using hashes here.

Provenance

The following attestation bundles were made for ptcmd-0.1.0b1.tar.gz:

Publisher: python-publish.yml on Visecy/ptcmd

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file ptcmd-0.1.0b1-py3-none-any.whl.

File metadata

  • Download URL: ptcmd-0.1.0b1-py3-none-any.whl
  • Upload date:
  • Size: 30.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.12.9

File hashes

Hashes for ptcmd-0.1.0b1-py3-none-any.whl
Algorithm Hash digest
SHA256 76bc2f03915815f90cbc616234a4f5a18614dfa66426f898fa4f97e08d10b11b
MD5 12a7eb8333333a56996ad61007da2d7d
BLAKE2b-256 06ddd9034e5539ce23a7e917059f52498918cd142eaa8fb91c7473242da1fb7f

See more details on using hashes here.

Provenance

The following attestation bundles were made for ptcmd-0.1.0b1-py3-none-any.whl:

Publisher: python-publish.yml on Visecy/ptcmd

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page