Interactive Command Sessions
The cmd
module offers a simple way to handle interactive sessions of commands. Each command is a line of text. The first word of each command is a verb defining the requested action. The rest of the line is passed as an argument to the method that implements the verb’s action.
Module cmd
supplies class Cmd
to use as a base class, and you define your own subclass of cmd.Cmd
. Your subclass supplies methods with names starting with do_
and help_
, and may optionally override some of Cmd
’s methods. When the user enters a command line such as verb and the rest
, as long as your subclass defines a method named do_
verb
, Cmd.onecmd
calls:
self.do_verb('and the rest')
Similarly, as long as your subclass defines a method named help_
verb
, Cmd.do_help
calls the method when the command line starts with 'help
verb
'
or '?
verb
'
. Cmd
, by default, shows suitable error messages if the user tries to use, or asks for help about, a verb for which the subclass does not define the needed method.
Initializing a Cmd Instance
Your subclass of cmd.Cmd
, if it defines its own _ _init_ _
special method, must call the base class’s _ _init_ _
, whose signature is as follows.
_ _init_ _ |
Initializes instance |
Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.