CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-cmd2

A tool for building interactive command line applications in Python

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

cmd2

A powerful tool for building interactive command line applications in Python. cmd2 extends Python's built-in cmd module with a wealth of features to make it quick and easy for developers to build feature-rich and user-friendly interactive command line applications.

Package Information

  • Package Name: cmd2
  • Package Type: pypi
  • Language: Python
  • Installation: pip install cmd2

Core Imports

import cmd2

For accessing the main Cmd class:

from cmd2 import Cmd

Common decorators and utilities:

from cmd2 import with_argparser, with_category, Settable
from cmd2 import style, fg, bg  # ANSI styling

Basic Usage

import cmd2
import argparse

class MyApp(cmd2.Cmd):
    """Example cmd2 application"""
    
    def __init__(self):
        super().__init__()
    
    def do_greet(self, args):
        """Say hello to someone"""
        if args:
            self.poutput(f"Hello, {args}!")
        else:
            self.poutput("Hello!")
    
    # Using argparse for command parsing
    parser = argparse.ArgumentParser()
    parser.add_argument('name', help='Name to greet')
    parser.add_argument('-s', '--shout', action='store_true', help='Shout the greeting')
    
    @cmd2.with_argparser(parser)
    def do_hello(self, args):
        """Advanced greeting with argparse"""
        greeting = f"Hello, {args.name}!"
        if args.shout:
            greeting = greeting.upper()
        self.poutput(greeting)

if __name__ == '__main__':
    app = MyApp()
    app.cmdloop()

Architecture

cmd2 is built around a main Cmd class that extends Python's standard cmd.Cmd with powerful additional features:

  • Command Processing: Built-in parsing, history, and execution framework
  • Argument Parsing: Integration with argparse for sophisticated command line parsing
  • I/O Redirection: Support for shell-like redirection with >, >>, and |
  • Scripting: Built-in support for command scripts and Python scripts
  • Extensibility: Plugin system and decorators for customization
  • Interactive Features: Tab completion, command history, and multi-line input

Capabilities

Core Command Framework

The main Cmd class that applications inherit from to create command-line interfaces.

class Cmd(cmd.Cmd):
    """An easy but powerful framework for writing line-oriented command interpreters."""
    
    def __init__(
        self,
        completekey: str = 'tab',
        stdin: Optional[TextIO] = None,
        stdout: Optional[TextIO] = None,
        *,
        persistent_history_file: str = '',
        persistent_history_length: int = 1000,
        startup_script: str = '',
        silence_startup_script: bool = False,
        include_py: bool = False,
        include_ipy: bool = False,
        allow_cli_args: bool = True,
        transcript_files: Optional[List[str]] = None,
        allow_redirection: bool = True,
        multiline_commands: Optional[List[str]] = None,
        terminators: Optional[List[str]] = None,
        shortcuts: Optional[Dict[str, str]] = None,
        command_sets: Optional[Iterable[CommandSet]] = None,
        auto_load_commands: bool = True,
    ) -> None: ...
    
    def cmdloop(self, intro: Optional[str] = None) -> None:
        """Repeatedly issue a prompt, accept input, parse and dispatch the command."""
    
    def onecmd_plus_hooks(self, line: str) -> bool:
        """Execute command and run all hooks."""
    
    def poutput(self, msg: Any = '', *, end: str = '\n') -> None:
        """Print message respecting output redirection."""
    
    def perror(self, msg: Any = '', *, end: str = '\n', apply_style: bool = True) -> None:
        """Print error message to stderr with optional styling."""
    
    def ppaged(self, msg: Any = '', *, end: str = '\n', chop: bool = False) -> None:
        """Print message using pager for long output."""

Command Decorators

Decorators for enhancing command methods with argument parsing and categorization.

def with_argparser(
    parser: argparse.ArgumentParser,
    *,
    ns_provider: Optional[Callable[..., argparse.Namespace]] = None,
    preserve_quotes: bool = False,
    with_unknown_args: bool = False,
) -> Callable[[CommandFunc], CommandFunc]:
    """Decorator to parse command arguments using argparse.ArgumentParser."""

def with_argument_list() -> Callable[[CommandFunc], CommandFunc]:
    """Decorator to pass arguments as a list rather than a string."""

def with_category(category: str) -> Callable[[CommandFunc], CommandFunc]:
    """Decorator to categorize commands for help display."""

def as_subcommand_to(
    command: str, 
    subcommand: str, 
    *, 
    help: Optional[str] = None
) -> Callable[[CommandFunc], CommandFunc]:
    """Decorator to register a function as a subcommand."""

ANSI Styling

Functions for adding colors and styles to terminal output.

def style(
    text: Any, 
    *, 
    fg: Optional[Union[FgColor, int, str]] = None,
    bg: Optional[Union[BgColor, int, str]] = None,
    bold: Optional[bool] = None,
    dim: Optional[bool] = None,
    italic: Optional[bool] = None,
    underline: Optional[bool] = None,
    strikethrough: Optional[bool] = None,
    overline: Optional[bool] = None,
    reverse: Optional[bool] = None,
    hidden: Optional[bool] = None
) -> str:
    """Apply ANSI color and style to text."""

# Color constants
class fg:
    """Foreground color constants"""
    BLACK: FgColor
    RED: FgColor
    GREEN: FgColor
    YELLOW: FgColor
    BLUE: FgColor
    MAGENTA: FgColor
    CYAN: FgColor
    WHITE: FgColor

class bg:
    """Background color constants"""
    BLACK: BgColor
    RED: BgColor
    GREEN: BgColor
    YELLOW: BgColor
    BLUE: BgColor
    MAGENTA: BgColor
    CYAN: BgColor
    WHITE: BgColor

Argument Parsing

Custom argument parser and completion classes extending argparse functionality.

class Cmd2ArgumentParser(argparse.ArgumentParser):
    """Custom ArgumentParser with better error formatting for cmd2."""
    
    def __init__(
        self,
        prog: Optional[str] = None,
        usage: Optional[str] = None,
        description: Optional[str] = None,
        epilog: Optional[str] = None,
        parents: Sequence[argparse.ArgumentParser] = [],
        formatter_class: argparse.HelpFormatter = argparse.RawDescriptionHelpFormatter,
        prefix_chars: str = '-',
        fromfile_prefix_chars: Optional[str] = None,
        argument_default: Any = None,
        conflict_handler: str = 'error',
        add_help: bool = True,
        allow_abbrev: bool = True,
    ) -> None: ...

class CompletionItem:
    """Represents a completion item with description."""
    
    def __init__(self, text: str, description: str = '') -> None: ...

def set_default_argument_parser(
    argument_parser_class: Type[argparse.ArgumentParser]
) -> None:
    """Set the default ArgumentParser class used by cmd2."""

Command Execution Results

Classes for handling command execution results and statements.

class CommandResult:
    """Contains the result of running a command via app() function."""
    
    def __init__(
        self, 
        stdout: str, 
        stderr: str, 
        data: Optional[Any] = None
    ) -> None:
        self.stdout = stdout
        self.stderr = stderr 
        self.data = data

class Statement:
    """Represents a parsed command statement."""
    
    command: str
    args: str
    arg_list: List[str]
    raw: str
    command_line: str
    multiline_command: str
    terminator: str = '\n'
    suffix: str = ''
    pipe_out: bool = False
    output_to: str = ''

Utilities and Settings

Utility functions and classes for application configuration.

class Settable:
    """A setting which can be changed via the 'set' command."""
    
    def __init__(
        self,
        name: str,
        val_type: Type,
        description: str,
        choices: Optional[Iterable[str]] = None,
        *,
        settable_object: Optional[Any] = None,
        onchange_cb: Optional[Callable[[str, str, str], None]] = None,
    ) -> None: ...

def categorize(
    func: Callable, 
    category: str
) -> Callable:
    """Categorize a command function."""

class CompletionMode(Enum):
    """Enum for tab completion modes."""
    SINGLE_TAB = "single"
    DOUBLE_TAB = "double"

class CommandSet:
    """Set of commands that can be installed into a cmd2 application."""
    
    def __init__(self) -> None: ...

Exception Classes

Exception types used throughout cmd2.

class Cmd2ArgparseError(Exception):
    """Raised when argparse has an error parsing arguments."""

class CommandSetRegistrationError(Exception):
    """Raised when a CommandSet fails to register."""

class CompletionError(Exception):
    """Raised when tab completion encounters an error."""

class SkipPostcommandHooks(Exception):
    """Raised to skip postcommand hooks."""

Constants

COMMAND_NAME: str  # Current command name attribute
DEFAULT_SHORTCUTS: Dict[str, str]  # Default single-character shortcuts
DEFAULT_ARGUMENT_PARSER: Type[argparse.ArgumentParser]  # Default parser class

Types

from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, TextIO, Type, Union
from enum import Enum
import argparse

# Type aliases
CommandFunc = Callable[..., Optional[bool]]
FgColor = Union[int, str]
BgColor = Union[int, str]

docs

index.md

tile.json