The cmd module contains only one class called Cmd. This is used as base class for a user defined framework for line oriented command line interpreters.
An object of this class or its subclass provides the line oriented interpreter framework. Important methods of this class inherited by the subclass are listed below.
This method sends the object in a loop, accepts inputs and sends the same to appropriate command handler method in the class.
As the loop starts an introductory message (give as parameter to cmdloop() method) will be displayed with a default (cmd) prompt which may be customized by prompt attribute.
The interpreter object recognizes the user input in two parts. First part prefixed with ‘do_’ is treated as method in the class and second part as the parameter to the method. For example if user enters ‘hello Python’, the interpreter tries to execute do_hello() method in the class sending ‘Python’ as parameter. If the said method is defined, it will be executed, otherwise error message will be displayed.
Subclass of Cmd inherits do_help() method. User’s input such as ‘help hello’ will fetch the docstring in the hello() method and display it as help text, or if present, help_hello() method will be run.
Following example demonstrates application of line oriented interpreter framework. The code first imports cmd module and defines a subclass of Cmd class.
The MathOps class defines add, sub, mul and div methods(all prefixed with do_ characters) with docstring text.
The object of MathOps class is declared and sent into a loop by calling cmdloop() method. When user types help in front of prompt, all method names are displayed. When name of a method with help is typed, the docstring of respective method is displayed. To call any of the methods, type its name , required arguments and press Enter. Result of the method will be displayed and prompt will come back repeatedly till ^D is issued to stop the loop.
from cmd import Cmd class MathOps(Cmd): def do_add(self, args): '''add two numbers''' num=args.split() print ('addition:',int(num)+int(num)) def do_sub(self, args): '''subtract two numbers''' num=args.split() print ('subtraction:',int(num)-int(num)) def do_mul(self, args): '''multiply two numbers''' num=args.split() print ('multiplication:',int(num)*int(num)) def do_div(self, args): '''perform division''' num=args.split() print ('division:',int(num)/int(num)) def do_EOF(self, args): return True op=MathOps() op.prompt= "->" op.cmdloop("loop starts. Press ^D to exit")
Sample run of above script is shown below
loop starts. Press ^D to exit ->help Documented commands (type help ): ======================================== add div help mul sub Undocumented commands: ====================== EOF ->help add add two numbers ->add 5 7 addition: 12 ->div 10 5 division: 2.0 -> >>>