Python cmd Module
Example
Define a tiny command interpreter and invoke a command method:
import cmd
class Hello(cmd.Cmd):
def do_hello(self, arg):
print(f"Hello, {arg}!")
h = Hello()
h.do_hello("Linus")
Try it Yourself »
Definition and Usage
The cmd module provides a simple framework for writing line-oriented command interpreters.
Use it to build REPL-like shells with command parsing, help, and tab completion support.
Members
Member | Description |
---|---|
Cmd | Base class for building command interpreters. |
cmdloop() | Enter the REPL loop to read and execute commands. |
columnize() | Format a list of strings into a multi-column display. |
completedefault() | Fallback tab completion when no complete_* is defined. |
complete() | Dispatch to complete_* methods for tab completion. |
completenames() | Return command names that match a given prefix. |
complete_help() | Tab completion for the built-in help command. |
default() | Handle an input line when no do_* handler exists. |
do_help() | Built-in help command that lists available commands and help text. |
emptyline() | Handle an empty input line (defaults to repeat last command). |
get_names() | Return a list of method names for commands and helpers. |
print_topics() | Helper used by do_help to format topic lists. |
onecmd() | Parse and execute a single command line string. |
parseline() | Parse a command line into command name and argument. |
postcmd() | Hook called after a command method returns; can modify loop flow. |
postloop() | Hook called once when the REPL loop is about to exit. |
precmd() | Hook called before a command is executed; can rewrite the line. |
preloop() | Hook called once before entering the REPL loop. |
setdefaultcompletekey() | Set default completion key (e.g., Tab). |
prompt | Prompt string shown before each input line (e.g., "(Cmd) " ). |
intro | Optional intro banner printed once when the loop starts. |
use_rawinput | Whether to use built-in input() for reading lines (default True). |
completekey | Key bound to completion in the REPL (default "tab" ). |
stdin | Input stream object used by the interpreter (defaults to sys.stdin). |
stdout | Output stream object used by the interpreter (defaults to sys.stdout). |
cmdqueue | Queue of command lines to process before prompting the user. |
ruler | Character used by help listing separators (default '-' ). |
doc_header | Header label for documented commands. |
misc_header | Header label for miscellaneous help topics. |
undoc_header | Header label for undocumented commands. |
nohelp | Message shown when no help is available for a topic. |
lastcmd | The last command line executed (used by emptyline() behavior). |