2 min read

Python Cmd Module

The cmd module provides a simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface.

Importing the Module

import cmd

Basic Usage

To use the cmd module, you create a subclass of cmd.Cmd and implement methods for the commands you want to support.

Creating a Command Processor

import cmd

class HelloWorld(cmd.Cmd):
    """Simple command processor example."""

    intro = 'Welcome to the hello shell.   Type help or ? to list commands.\n'
    prompt = '(hello) '

    def do_greet(self, line):
        """greet [person]
        Greet the named person"""
        if line:
            print(f"Hello, {line}")
        else:
            print("Hello")

    def do_EOF(self, line):
        return True

if __name__ == '__main__':
    HelloWorld().cmdloop()

Command Methods

Commands are defined by creating methods with the prefix do_. The part of the method name after do_ becomes the command name.

  • do_command(self, arg): This method is called when the user types command. The arg parameter contains the rest of the line.

Help Methods

You can provide help for your commands by defining methods with the prefix help_.

  • help_command(self): This method is called when the user types help command.

Hooks and Overrides

The cmd.Cmd class provides several methods that can be overridden to customize behavior.

  • preloop(): Called once before the command loop starts.
  • postloop(): Called once after the command loop ends.
  • emptyline(): Called when an empty line is entered. By default, it repeats the last command.
  • default(line): Called when an unknown command is entered.

Quitting

To exit the command loop, a command method should return True. Typically, this is done in a do_EOF or do_quit method.

    def do_quit(self, line):
        return True

programming/python/python