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):

 def help_quit(self):
 print "syntax: quit",
 print "-- terminates the application"

 # shortcuts
 do_q = do_quit

# try it out

cli = CLI()

> help

Documented commands (type help ):
hello quit

Undocumented commands:
help q

> hello world
hello again world !
> q

Core Modules

More Standard Modules

Threads and Processes

Data Representation

File Formats

Mail and News Message Processing

Network Protocols


Multimedia Modules

Data Storage

Tools and Utilities

Platform-Specific Modules

Implementation Support Modules

Other Modules

show all menu

Python Standard Library
Python Standard Library (Nutshell Handbooks) with
ISBN: 0596000960
EAN: 2147483647
Year: 2000
Pages: 252
Authors: Fredrik Lundh
Similar book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net