On this page
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
- Arguments arrive as one raw string:
cmd.Cmdsplits only the first word as the command name. Use shlex (shlex.split(arg)) if you need quoted arguments. - Empty lines repeat the last command by default: Override
emptyline(self)to returnNoneif pressing Enter should do nothing. - Unhandled
Ctrl-D(EOF): Always implementdo_EOFreturningTrueso piped input orCtrl-Dexits cleanly instead of printing*** Unknown syntax: EOF. - Single-line oriented: For multi-line editing, syntax highlighting, or async prompts, use a third-party library like
prompt_toolkit.
Classes & Objects
- cmd.Cmd — A simple framework for writing line-oriented command interpreters. (Methods:
.cmdloop(),.columnize(),.complete(),.complete_help(),.completedefault(),.completenames())
Linked from
Related notes
- tuts/python3/stdlib_module/cmath Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/code Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/readline Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/bdb links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/cmd/Cmd Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/colorsys Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/curses Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/gettext Linked here; shared tags: #stdlib