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
