On this page
  1. cmd
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Adding Tab Completion and Shorthand Arguments
  7. 2. Driving cmd.Cmd in Tests or Scripts
  8. Gotchas & Boundaries
  9. Classes & Objects

cmd

Prev: cmath | Up: stdlib_module | Next: code
Rel: wave, colorsys, gettext, locale, turtle
Ref: docs.python.org — cmd
Tags: #public #python3 #stdlib


Import

import cmd

Overview

Framework for building line-oriented interactive command shells (REPLs) with built-in prompt handling, help generation, tab completion, and command history (when readline is available). Reach for cmd when building an admin console, debugger, or interactive CLI tool without pulling in a full TUI framework like curses.

Quick Start

import cmd

class CalcShell(cmd.Cmd):
    intro = "Type 'add 2 3' or 'quit'."
    prompt = "calc> "

    def do_add(self, arg: str) -> None:
        """Add space-separated integers: add 2 3"""
        nums = [int(x) for x in arg.split()]
        print(sum(nums))

    def do_quit(self, arg: str) -> bool:
        """Exit the shell."""
        return True

shell = CalcShell()
shell.onecmd("add 2 3")   # prints 5

Implementation Walkthrough

1. Adding Tab Completion and Shorthand Arguments

Prefix handler methods with do_<command> and optional completion methods with complete_<command>. Returning a truthy value from any do_* method exits cmdloop():

import cmd

class TaskShell(cmd.Cmd):
    prompt = "todo> "
    PRIORITIES = ("low", "medium", "high")

    def __init__(self) -> None:
        super().__init__()
        self.items: list[tuple[str, str]] = []

    def do_new(self, arg: str) -> None:
        """Create a task: new <priority> <title>"""
        parts = arg.split(maxsplit=1)
        if len(parts) != 2:
            print("Usage: new <low|medium|high> <title>")
            return
        self.items.append((parts[0], parts[1]))

    def complete_new(self, text: str, line: str, begidx: int, endidx: int) -> list[str]:
        return [p for p in self.PRIORITIES if p.startswith(text)]

    def do_EOF(self, arg: str) -> bool:
        print()
        return True

2. Driving cmd.Cmd in Tests or Scripts

Pass custom stdin/stdout streams (like io.StringIO) and set use_rawinput = False to run deterministic, non-interactive tests against your shell:

import io

out = io.StringIO()
shell = TaskShell()
shell.stdout = out
shell.use_rawinput = False
shell.onecmd("new high Ship docs")
assert shell.items == [("high", "Ship docs")]

Gotchas & Boundaries

Classes & Objects

Linked from

Related notes