liveBook · Manning

Cmd module

As explained in Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi

The cmd module is a Python standard-library module that provides a framework for building interactive command interpreters.

The cmd module is a Python standard-library framework for building interactive command interpreters, including a REPL robot shell. Subclass cmd.Cmd, define a prompt and welcome message, and implement do_<command> methods that respond to user input. section 4.5

A basic command interpreter follows this pattern:

  • Import cmd and the hardware-control library. section 4.5
  • Subclass cmd.Cmd and set intro and prompt text. section 4.5
  • Define do_forward, do_backward, and similar handlers for commands. section 4.5
  • Start cmdloop() to read input and execute handlers. section 4.5
  • Use help, command history, tab completion, SSH access, and CTRL+C during operation. section 4.5
Listing 4.1 basic_shell.py: Providing basic robot movements in a shell
#!/usr/bin/env python3
import cmd
import motor
 
class RobotShell(cmd.Cmd):
    intro = 'Welcome to the robot shell. Type help or ? to list commands.'
    prompt = '(robot) '
 
    def do_forward(self, line):
        motor.forward()
 
    def do_backward(self, line):
        motor.backward()
 
RobotShell().cmdloop()

A complete basic_shell.py example connects cmd.Cmd handlers to forward and backward motor actions. section 4.5

How Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi covers it

How deep it goes
Explains subclassing, command handlers, and the event loop, while deferring broader library details to documentation.
Examples
Uses a robot shell with forward and backward commands, help output, history, tab completion, and saved-command input.
What it assumes
Assumes Python and an existing motor library, while introducing the shell structure and command-dispatch pattern.
What you can do after
Build it from scratch as a Python shell that dispatches user commands to reusable robot-control functions.
How it connects
Connects REPLs, Python standard-library modules, motor-control libraries, SSH, and command-line interaction.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi. The section links point to the parts of the book it draws on.