This wiki is in the process of being archived due to lack of usage and the resources necessary to serve it — predominately to bots, crawlers, and LLM companies. Edits are discouraged.
Pages are preserved as they were at the time of archival. For current information, please visit python.org.
If a change to this archive is absolutely needed, requests can be made via the infrastructure@python.org mailing list.

The cmd module makes it easy to make command line interfaces in your programs.

cmd is different than OptParse, in that OptParse is a tool for making command line tools.

cmd, on the other hand, makes it so you can embed a command line within your program.

In these days of graphical user interfaces, a command line interpreter seems antique. I agree that GUIs are often more friendly (and in fact I'm happy to have something other than "ed" to create this document). But a command line interface can have several advantages:

And even if you plan to create GUI software, it's often good to start with a text interface. This will allow you to focus on the applicative logic independently of the interface. This is often a good way to create modular software.

cmd module basics

The module defines only one class: the Cmd class. Creating a command line interpreter is done by sub-classing the cmd.Cmd class.

Creating a command

The main goal of an interpreter is to respond to commands. A command is the first part of a line of text entered at the interpreter prompt. This part is defined as the longest string of characters contained in the identchars member. By default identchars contains non accented letters, digits and the underscore symbol. The end of the line is the command's parameters.

Command handling is really easy: if you want to define the command spam, you only have to define the do_spam method in your derived class.

parameters

The do_xxx method should only take one extra parameter. This parameter corresponds to the part of the string entered by the user after the command name. The job of do_xxx is to parse this string and to find the command parameter's values. Python provides many helpful tools to parse this string, but this is quite out of the scope of his how-to.

errors

The interpreter uses the following format to signal errors:

*** <error description>: <additional parameters>

It's generally a good idea to use the same format for application errors.

return value

In the most common case: commands shouldn't return a value. The exception is when you want to exit the interpreter loop: any command that returns a true value stops the interpreter.

sample

The following function defines a command which takes two numerical arguments and prints the result of the addition:

def do_add(self,s):
    l = s.split()
    if len(l)!=2:
       print "*** invalid number of arguments"
       return
    try:
       l = [int(i) for i in l]
    except ValueError:
       print "*** arguments should be numbers"
       return
    print l[0]+l[1]

Now if you run the interpreter, you will have:

(Cmd) add 4
*** invalid number of arguments
(Cmd) add 5 4
9

Help

Help support is another strength of the cmd module. You can provide documentation for the xxx command by defining the help_xxx method. For the add command, you could for example define:

def help_add(self):
    print 'add two integral numbers'

And then, in the interactive interpreter you will have:

(Cmd) help add
add two integral numbers

You can also define help for topics that are not related to commands:

def help_introduction(self):
    print 'introduction'
    print 'a good place for a tutorial'

The interpreter understands the ? character as a shortcut for the help command.

Completion

Completion is a very interesting feature: when the user presses the TAB key, the interpreter will try to complete the command or propose several alternatives. Completion will be available only if the computer supports the readline module. You can disable completion by passing the None value to the completekey attribute of the Cmd class constructor.

The interpreter is able to process completion for commands names, but for commands arguments you will have to help it. For the command xxx, this is done by defining a complete_xxx method. For example, if you have defined a color command, the completion method for this command could be:

_AVAILABLE_COLORS = ('blue', 'green', 'yellow', 'red', 'black')
def complete_color(self, text, line, begidx, endidx):
    return [i for i in _AVAILABLE_COLORS if i.startswith(text)]

The complete_xxx method takes four arguments:

It should return a list (possibly empty) of strings representing the possible completions. The arguments begidx and endidx are useful when completion depends on the position of the argument.

Starting the interpreter

Once you have defined your own interpreter class, the only thing left to do is to create an instance and to call the mainloop method:

interpreter = MyCmdInterpreter()
interpreter.cmdloop()

In python 2.1 and 2.2 (and possibly some older, as well as future releases?) mainloop() has been renamed to cmdloop()

Interface customization

The cmd module provides several hooks to change the behavior of the interpreter. You should note that your users won't necessary thank you should you deviate from the standard behavior.

Empty lines

By default when an empty line is entered, the last command is repeated. You can change this behavior by overriding the emptyline method. For example to disable the repetition of the last command:

def emptyline(self):
    pass

Help summary

When the help command is called without arguments, it prints a summary of all the documentation topics:

(Cmd) help
Documented commands (type help <topic>):
========================================
EOF add exit macro shell test
Miscellaneous help topics:
==========================
intro
Undocumented commands:
======================
line help
(Cmd)

This summary is separated into three parts:

You can customize this screen with several data members:

Introduction message

At startup, the interpreter print the self.intro string. This string can be overridden via an optional argument to the cmdloop() method.

Advanced material

Defaults handling

Theses methods have the same parameters as the do_xxx and complete_xxx methods.

Nested interpreters

If your program becomes complex, or if your data structure is hierarchical, it can be interesting to define nested interpreters (calling an interpreter inside an other interpreter). In that case, I like having a prompt like:

(Cmd) test
(Cmd:Test) exit
(Cmd)

You can do this by changing the prompt attribute of the nested interpreter:

def do_test(self, s):
    i = TestCmd()
    i.prompt = self.prompt[:-1]+':Test)'
    i.cmdloop()

Note that it can be a better practice to do this in the constructor of the nested interpreter.

Sometimes, it can be useful to have a more directed, interactive session with the users. The Cmd class allows you to use the print and raw_input functions without any problems:

def do_hello(self, s):
    if s=='':
        s = raw_input('Your name please: ')
    print 'Hello',s

FIXME: How to change completion behavior of raw_input?

The interpreter loop

At the start of the interpreter loop the preloop method is called, and at the end of the loop the postloop method is called. These methods take no arguments, and return no values. The following shows how to make the interpreter more polite:

class polite_cmd(cmd.Cmd,object):