The cmd Module
The cmd module (see Example 14-5) provides a simple framework for command-line interfaces (CLI). This is used by the pdb debugger module, but you can also use it for your own programs.
To implement your own command-line interface, subclass the Cmd class, and define do and help methods. The base class automatically turns all do methods into commands and uses the help methods to show help information.
Example 14-5. Using the cmd Module
File: cmd-example-1.py
import cmd
import string, sys
class CLI(cmd.Cmd):
def _ _init_ _(self):
cmd.Cmd._ _init_ _(self)
self.prompt = >
def do_hello(self, arg):
print "hello again", arg, "!"
def help_hello(self):
print "syntax: hello [message]",
print "-- prints a hello message"
def do_quit(self, arg):
sys.exit(1)
def help_quit(self):
print "syntax: quit",
print "-- terminates the application"
# shortcuts
do_q = do_quit
#
# try it out
cli = CLI()
cli.cmdloop()
> help
Documented commands (type help
Категории