cmd
The Python cmd module provides a framework for building line-oriented command interpreters. It supplies a single class, Cmd, that you subclass to create custom interactive shells, administrative tools, and test harnesses with a built-in help system and optional tab completion.
Here’s a minimal shell:
greet_shell.py
import cmd
class GreetShell(cmd.Cmd):
prompt = "(greet) "
def do_hello(self, arg):
"""Say hello: HELLO name"""
print(f"Hello, {arg or 'world'}!")
def do_quit(self, arg):
"""Exit the shell."""
return True
GreetShell().cmdloop()
Run it on the command line:
$ python greet_shell.py
(greet) hello Pythonista
Hello, Pythonista!
(greet) quit
The shell recognizes hello and quit as commands because the class defines .do_hello() and .do_quit() methods.
Key Features
- Dispatches input lines to
.do_<command>()methods automatically - Generates a
helpcommand from method docstrings with no extra code - Supports Tab completion via Readline when available
- Provides hook methods for setup, teardown, and per-command processing
- Accepts
?as an alias forhelpand!as an alias for a shell command - Reads from a queue of pre-loaded commands via
cmdqueue
Frequently Used Classes and Methods
| Object | Type | Description |
|---|---|---|
cmd.Cmd |
Class | Provides a base class for line-oriented command interpreters |
Cmd.cmdloop() |
Method | Starts the prompt loop and processes commands until stopped |
Cmd.onecmd() |
Method | Parses and dispatches a single command string |
Cmd.default() |
Method | Is called when the command prefix is not recognized |
Cmd.emptyline() |
Method | Is called when an empty line is entered at the prompt |
Cmd.precmd() |
Method | Hook called just before a command line is dispatched |
Cmd.postcmd() |
Method | Hook called just after a command line is dispatched |
Examples
Overriding .default() to handle unrecognized commands gracefully:
shell.py
import cmd
class MyShell(cmd.Cmd):
prompt = "(shell) "
def default(self, line):
print(f"Unknown command: {line!r}. Type 'help' for a list of commands.")
def do_quit(self, arg):
"""Exit the shell."""
return True
Overriding .emptyline() to do nothing instead of repeating the last command:
shell.py
def emptyline(self):
pass
Adding tab-completion for a command’s arguments:
shell.py
COLORS = ["red", "green", "blue"]
def do_paint(self, arg):
"""Paint a color: PAINT color"""
print(f"Painting {arg}.")
def complete_paint(self, text, line, begidx, endidx):
return [c for c in COLORS if c.startswith(text)]
Common Use Cases
The most common tasks for cmd include:
Real-World Example
A minimal task-list shell that lets a user add and list tasks interactively:
task_shell.py
import cmd
class TaskShell(cmd.Cmd):
intro = "Task Shell. Type help or ? to list commands.\n"
prompt = "(tasks) "
def __init__(self):
super().__init__()
self.tasks = []
def do_add(self, arg):
"""Add a task: ADD description"""
if arg:
self.tasks.append(arg)
print(f"Added: {arg!r}")
def do_list(self, arg):
"""List all tasks."""
if self.tasks:
for i, task in enumerate(self.tasks, 1):
print(f" {i}. {task}")
else:
print("No tasks yet.")
def do_quit(self, arg):
"""Exit the shell."""
return True
if __name__ == "__main__":
TaskShell().cmdloop()
Run it on the command line:
$ python task_shell.py
Task Shell. Type help or ? to list commands.
(tasks) add Buy groceries
Added: 'Buy groceries'
(tasks) add Write tests
Added: 'Write tests'
(tasks) list
1. Buy groceries
2. Write tests
(tasks) quit
The shell gains a working help command automatically from the method docstrings.
Related Resources
Tutorial
Build Command-Line Interfaces With Python's argparse
In this step-by-step Python tutorial, you'll learn how to take your command-line Python scripts to the next level by adding a convenient command-line interface (CLI) that you can write with the argparse module from the standard library.
For additional information on related topics, take a look at the following resources:
- Object-Oriented Programming (OOP) in Python (Tutorial)
- Building Command Line Interfaces With argparse (Course)
- Build Command-Line Interfaces With Python's argparse (Quiz)
- A Conceptual Primer on OOP in Python (Course)
- Intro to Object-Oriented Programming (OOP) in Python (Course)
- Object-Oriented Programming (OOP) in Python (Quiz)
By Leodanis Pozo Ramos • Updated March 2, 2026