Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes
cmd.Cmd Class Reference
Inheritance diagram for cmd.Cmd:
Inheritance graph
[legend]
Collaboration diagram for cmd.Cmd:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def cmdloop
def precmd
def postcmd
def preloop
def postloop
def parseline
def onecmd
def emptyline
def default
def completedefault
def completenames
def complete
def get_names
def complete_help
def do_help
def print_topics
def columnize

Public Attributes

 stdin
 stdout
 cmdqueue
 completekey
 old_completer
 lastcmd
 completion_matches

Static Public Attributes

 prompt = PROMPT
 identchars = IDENTCHARS
string ruler = '='
string lastcmd = ''
 intro = None
string doc_leader = ""
string doc_header = "Documented commands (type help <topic>):"
string misc_header = "Miscellaneous help topics:"
string undoc_header = "Undocumented commands:"
string nohelp = "*** No help on %s"
int use_rawinput = 1

Detailed Description

A simple framework for writing line-oriented command interpreters.

These are often useful for test harnesses, administrative tools, and
prototypes that will later be wrapped in a more sophisticated interface.

A Cmd instance or subclass instance is a line-oriented interpreter
framework.  There is no good reason to instantiate Cmd itself; rather,
it's useful as a superclass of an interpreter class you define yourself
in order to inherit Cmd's methods and encapsulate action methods.

Definition at line 52 of file cmd.py.


Constructor & Destructor Documentation

def cmd.Cmd.__init__ (   self,
  completekey = 'tab',
  stdin = None,
  stdout = None 
)
Instantiate a line-oriented interpreter framework.

The optional argument 'completekey' is the readline name of a
completion key; it defaults to the Tab key. If completekey is
not None and the readline module is available, command completion
is done automatically. The optional arguments stdin and stdout
specify alternate input and output file objects; if not specified,
sys.stdin and sys.stdout are used.

Definition at line 76 of file cmd.py.

00076 
00077     def __init__(self, completekey='tab', stdin=None, stdout=None):
00078         """Instantiate a line-oriented interpreter framework.
00079 
00080         The optional argument 'completekey' is the readline name of a
00081         completion key; it defaults to the Tab key. If completekey is
00082         not None and the readline module is available, command completion
00083         is done automatically. The optional arguments stdin and stdout
00084         specify alternate input and output file objects; if not specified,
00085         sys.stdin and sys.stdout are used.
00086 
00087         """
00088         if stdin is not None:
00089             self.stdin = stdin
00090         else:
00091             self.stdin = sys.stdin
00092         if stdout is not None:
00093             self.stdout = stdout
00094         else:
00095             self.stdout = sys.stdout
00096         self.cmdqueue = []
00097         self.completekey = completekey

Here is the caller graph for this function:


Member Function Documentation

def cmd.Cmd.cmdloop (   self,
  intro = None 
)
Repeatedly issue a prompt, accept input, parse an initial prefix
off the received input, and dispatch to action methods, passing them
the remainder of the line as argument.

Definition at line 98 of file cmd.py.

00098 
00099     def cmdloop(self, intro=None):
00100         """Repeatedly issue a prompt, accept input, parse an initial prefix
00101         off the received input, and dispatch to action methods, passing them
00102         the remainder of the line as argument.
00103 
00104         """
00105 
00106         self.preloop()
00107         if self.use_rawinput and self.completekey:
00108             try:
00109                 import readline
00110                 self.old_completer = readline.get_completer()
00111                 readline.set_completer(self.complete)
00112                 readline.parse_and_bind(self.completekey+": complete")
00113             except ImportError:
00114                 pass
00115         try:
00116             if intro is not None:
00117                 self.intro = intro
00118             if self.intro:
00119                 self.stdout.write(str(self.intro)+"\n")
00120             stop = None
00121             while not stop:
00122                 if self.cmdqueue:
00123                     line = self.cmdqueue.pop(0)
00124                 else:
00125                     if self.use_rawinput:
00126                         try:
00127                             line = input(self.prompt)
00128                         except EOFError:
00129                             line = 'EOF'
00130                     else:
00131                         self.stdout.write(self.prompt)
00132                         self.stdout.flush()
00133                         line = self.stdin.readline()
00134                         if not len(line):
00135                             line = 'EOF'
00136                         else:
00137                             line = line.rstrip('\r\n')
00138                 line = self.precmd(line)
00139                 stop = self.onecmd(line)
00140                 stop = self.postcmd(stop, line)
00141             self.postloop()
00142         finally:
00143             if self.use_rawinput and self.completekey:
00144                 try:
00145                     import readline
00146                     readline.set_completer(self.old_completer)
00147                 except ImportError:
00148                     pass
00149 

Here is the call graph for this function:

Here is the caller graph for this function:

def cmd.Cmd.columnize (   self,
  list,
  displaywidth = 80 
)
Display a list of strings as a compact set of columns.

Each column is only as wide as necessary.
Columns are separated by two spaces (one was not legible enough).

Definition at line 344 of file cmd.py.

00344 
00345     def columnize(self, list, displaywidth=80):
00346         """Display a list of strings as a compact set of columns.
00347 
00348         Each column is only as wide as necessary.
00349         Columns are separated by two spaces (one was not legible enough).
00350         """
00351         if not list:
00352             self.stdout.write("<empty>\n")
00353             return
00354 
00355         nonstrings = [i for i in range(len(list))
00356                         if not isinstance(list[i], str)]
00357         if nonstrings:
00358             raise TypeError("list[i] not a string for i in %s"
00359                             % ", ".join(map(str, nonstrings)))
00360         size = len(list)
00361         if size == 1:
00362             self.stdout.write('%s\n'%str(list[0]))
00363             return
00364         # Try every row count from 1 upwards
00365         for nrows in range(1, len(list)):
00366             ncols = (size+nrows-1) // nrows
00367             colwidths = []
00368             totwidth = -2
00369             for col in range(ncols):
00370                 colwidth = 0
00371                 for row in range(nrows):
00372                     i = row + nrows*col
00373                     if i >= size:
00374                         break
00375                     x = list[i]
00376                     colwidth = max(colwidth, len(x))
00377                 colwidths.append(colwidth)
00378                 totwidth += colwidth + 2
00379                 if totwidth > displaywidth:
00380                     break
00381             if totwidth <= displaywidth:
00382                 break
00383         else:
00384             nrows = len(list)
00385             ncols = 1
00386             colwidths = [0]
00387         for row in range(nrows):
00388             texts = []
00389             for col in range(ncols):
00390                 i = row + nrows*col
00391                 if i >= size:
00392                     x = ""
00393                 else:
00394                     x = list[i]
00395                 texts.append(x)
00396             while texts and not texts[-1]:
00397                 del texts[-1]
00398             for col in range(len(texts)):
00399                 texts[col] = texts[col].ljust(colwidths[col])
00400             self.stdout.write("%s\n"%str("  ".join(texts)))

Here is the call graph for this function:

Here is the caller graph for this function:

def cmd.Cmd.complete (   self,
  text,
  state 
)
Return the next possible completion for 'text'.

If a command has not been entered, then complete against command list.
Otherwise try to call complete_<command> to get list of completions.

Definition at line 249 of file cmd.py.

00249 
00250     def complete(self, text, state):
00251         """Return the next possible completion for 'text'.
00252 
00253         If a command has not been entered, then complete against command list.
00254         Otherwise try to call complete_<command> to get list of completions.
00255         """
00256         if state == 0:
00257             import readline
00258             origline = readline.get_line_buffer()
00259             line = origline.lstrip()
00260             stripped = len(origline) - len(line)
00261             begidx = readline.get_begidx() - stripped
00262             endidx = readline.get_endidx() - stripped
00263             if begidx>0:
00264                 cmd, args, foo = self.parseline(line)
00265                 if cmd == '':
00266                     compfunc = self.completedefault
00267                 else:
00268                     try:
00269                         compfunc = getattr(self, 'complete_' + cmd)
00270                     except AttributeError:
00271                         compfunc = self.completedefault
00272             else:
00273                 compfunc = self.completenames
00274             self.completion_matches = compfunc(text, line, begidx, endidx)
00275         try:
00276             return self.completion_matches[state]
00277         except IndexError:
00278             return None

Here is the call graph for this function:

def cmd.Cmd.complete_help (   self,
  args 
)

Definition at line 284 of file cmd.py.

00284 
00285     def complete_help(self, *args):
00286         commands = set(self.completenames(*args))
00287         topics = set(a[5:] for a in self.get_names()
00288                      if a.startswith('help_' + args[0]))
00289         return list(commands | topics)

Here is the call graph for this function:

def cmd.Cmd.completedefault (   self,
  ignored 
)
Method called to complete an input line when no command-specific
complete_*() method is available.

By default, it returns an empty list.

Reimplemented in test.test_cmd.samplecmdclass.

Definition at line 236 of file cmd.py.

00236 
00237     def completedefault(self, *ignored):
00238         """Method called to complete an input line when no command-specific
00239         complete_*() method is available.
00240 
00241         By default, it returns an empty list.
00242 
00243         """
00244         return []

Here is the caller graph for this function:

def cmd.Cmd.completenames (   self,
  text,
  ignored 
)

Definition at line 245 of file cmd.py.

00245 
00246     def completenames(self, text, *ignored):
00247         dotext = 'do_'+text
00248         return [a[3:] for a in self.get_names() if a.startswith(dotext)]

Here is the call graph for this function:

Here is the caller graph for this function:

def cmd.Cmd.default (   self,
  line 
)
Called on an input line when the command prefix is not recognized.

If this method is not overridden, it prints an error message and
returns.

Reimplemented in pdb.Pdb.

Definition at line 227 of file cmd.py.

00227 
00228     def default(self, line):
00229         """Called on an input line when the command prefix is not recognized.
00230 
00231         If this method is not overridden, it prints an error message and
00232         returns.
00233 
00234         """
00235         self.stdout.write('*** Unknown syntax: %s\n'%line)

Here is the caller graph for this function:

def cmd.Cmd.do_help (   self,
  arg 
)

Reimplemented in pdb.Pdb.

Definition at line 290 of file cmd.py.

00290 
00291     def do_help(self, arg):
00292         'List available commands with "help" or detailed help with "help cmd".'
00293         if arg:
00294             # XXX check arg syntax
00295             try:
00296                 func = getattr(self, 'help_' + arg)
00297             except AttributeError:
00298                 try:
00299                     doc=getattr(self, 'do_' + arg).__doc__
00300                     if doc:
00301                         self.stdout.write("%s\n"%str(doc))
00302                         return
00303                 except AttributeError:
00304                     pass
00305                 self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
00306                 return
00307             func()
00308         else:
00309             names = self.get_names()
00310             cmds_doc = []
00311             cmds_undoc = []
00312             help = {}
00313             for name in names:
00314                 if name[:5] == 'help_':
00315                     help[name[5:]]=1
00316             names.sort()
00317             # There can be duplicates if routines overridden
00318             prevname = ''
00319             for name in names:
00320                 if name[:3] == 'do_':
00321                     if name == prevname:
00322                         continue
00323                     prevname = name
00324                     cmd=name[3:]
00325                     if cmd in help:
00326                         cmds_doc.append(cmd)
00327                         del help[cmd]
00328                     elif getattr(self, name).__doc__:
00329                         cmds_doc.append(cmd)
00330                     else:
00331                         cmds_undoc.append(cmd)
00332             self.stdout.write("%s\n"%str(self.doc_leader))
00333             self.print_topics(self.doc_header,   cmds_doc,   15,80)
00334             self.print_topics(self.misc_header,  list(help.keys()),15,80)
00335             self.print_topics(self.undoc_header, cmds_undoc, 15,80)

Here is the call graph for this function:

Here is the caller graph for this function:

def cmd.Cmd.emptyline (   self)
Called when an empty line is entered in response to the prompt.

If this method is not overridden, it repeats the last nonempty
command entered.

Definition at line 217 of file cmd.py.

00217 
00218     def emptyline(self):
00219         """Called when an empty line is entered in response to the prompt.
00220 
00221         If this method is not overridden, it repeats the last nonempty
00222         command entered.
00223 
00224         """
00225         if self.lastcmd:
00226             return self.onecmd(self.lastcmd)

Here is the call graph for this function:

Here is the caller graph for this function:

def cmd.Cmd.get_names (   self)

Definition at line 279 of file cmd.py.

00279 
00280     def get_names(self):
00281         # This method used to pull in base class attributes
00282         # at a time dir() didn't do it yet.
00283         return dir(self.__class__)

Here is the caller graph for this function:

def cmd.Cmd.onecmd (   self,
  line 
)
Interpret the argument as though it had been typed in response
to the prompt.

This may be overridden, but should not normally need to be;
see the precmd() and postcmd() methods for useful execution hooks.
The return value is a flag indicating whether interpretation of
commands by the interpreter should stop.

Reimplemented in pdb.Pdb.

Definition at line 192 of file cmd.py.

00192 
00193     def onecmd(self, line):
00194         """Interpret the argument as though it had been typed in response
00195         to the prompt.
00196 
00197         This may be overridden, but should not normally need to be;
00198         see the precmd() and postcmd() methods for useful execution hooks.
00199         The return value is a flag indicating whether interpretation of
00200         commands by the interpreter should stop.
00201 
00202         """
00203         cmd, arg, line = self.parseline(line)
00204         if not line:
00205             return self.emptyline()
00206         if cmd is None:
00207             return self.default(line)
00208         self.lastcmd = line
00209         if cmd == '':
00210             return self.default(line)
00211         else:
00212             try:
00213                 func = getattr(self, 'do_' + cmd)
00214             except AttributeError:
00215                 return self.default(line)
00216             return func(arg)

Here is the call graph for this function:

Here is the caller graph for this function:

def cmd.Cmd.parseline (   self,
  line 
)
Parse the line into a command name and a string containing
the arguments.  Returns a tuple containing (command, args, line).
'command' and 'args' may be None if the line couldn't be parsed.

Definition at line 172 of file cmd.py.

00172 
00173     def parseline(self, line):
00174         """Parse the line into a command name and a string containing
00175         the arguments.  Returns a tuple containing (command, args, line).
00176         'command' and 'args' may be None if the line couldn't be parsed.
00177         """
00178         line = line.strip()
00179         if not line:
00180             return None, None, line
00181         elif line[0] == '?':
00182             line = 'help ' + line[1:]
00183         elif line[0] == '!':
00184             if hasattr(self, 'do_shell'):
00185                 line = 'shell ' + line[1:]
00186             else:
00187                 return None, None, line
00188         i, n = 0, len(line)
00189         while i < n and line[i] in self.identchars: i = i+1
00190         cmd, arg = line[:i], line[i:].strip()
00191         return cmd, arg, line

Here is the caller graph for this function:

def cmd.Cmd.postcmd (   self,
  stop,
  line 
)
Hook method executed just after a command dispatch is finished.

Reimplemented in pstats.ProfileBrowser.

Definition at line 157 of file cmd.py.

00157 
00158     def postcmd(self, stop, line):
00159         """Hook method executed just after a command dispatch is finished."""
00160         return stop

def cmd.Cmd.postloop (   self)
Hook method executed once when the cmdloop() method is about to
return.

Reimplemented in test.test_cmd.samplecmdclass.

Definition at line 165 of file cmd.py.

00165 
00166     def postloop(self):
00167         """Hook method executed once when the cmdloop() method is about to
00168         return.
00169 
00170         """
00171         pass

def cmd.Cmd.precmd (   self,
  line 
)
Hook method executed just before the command line is
interpreted, but after the input prompt is generated and issued.

Reimplemented in pdb.Pdb.

Definition at line 150 of file cmd.py.

00150 
00151     def precmd(self, line):
00152         """Hook method executed just before the command line is
00153         interpreted, but after the input prompt is generated and issued.
00154 
00155         """
00156         return line

def cmd.Cmd.preloop (   self)
Hook method executed once when the cmdloop() method is called.

Reimplemented in pdb.Pdb, and test.test_cmd.samplecmdclass.

Definition at line 161 of file cmd.py.

00161 
00162     def preloop(self):
00163         """Hook method executed once when the cmdloop() method is called."""
00164         pass

Here is the caller graph for this function:

def cmd.Cmd.print_topics (   self,
  header,
  cmds,
  cmdlen,
  maxcol 
)

Definition at line 336 of file cmd.py.

00336 
00337     def print_topics(self, header, cmds, cmdlen, maxcol):
00338         if cmds:
00339             self.stdout.write("%s\n"%str(header))
00340             if self.ruler:
00341                 self.stdout.write("%s\n"%str(self.ruler * len(header)))
00342             self.columnize(cmds, maxcol-1)
00343             self.stdout.write("\n")

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

Reimplemented in pdb.Pdb.

Definition at line 95 of file cmd.py.

Definition at line 96 of file cmd.py.

Definition at line 273 of file cmd.py.

string cmd.Cmd.doc_header = "Documented commands (type help <topic>):" [static]

Definition at line 70 of file cmd.py.

string cmd.Cmd.doc_leader = "" [static]

Definition at line 69 of file cmd.py.

Definition at line 65 of file cmd.py.

cmd.Cmd.intro = None [static]

Definition at line 68 of file cmd.py.

string cmd.Cmd.lastcmd = '' [static]

Reimplemented in pdb.Pdb.

Definition at line 67 of file cmd.py.

Reimplemented in pdb.Pdb.

Definition at line 207 of file cmd.py.

string cmd.Cmd.misc_header = "Miscellaneous help topics:" [static]

Definition at line 71 of file cmd.py.

string cmd.Cmd.nohelp = "*** No help on %s" [static]

Definition at line 73 of file cmd.py.

Definition at line 109 of file cmd.py.

cmd.Cmd.prompt = PROMPT [static]

Reimplemented in pstats.ProfileBrowser, and pdb.Pdb.

Definition at line 64 of file cmd.py.

string cmd.Cmd.ruler = '=' [static]

Definition at line 66 of file cmd.py.

Definition at line 88 of file cmd.py.

Definition at line 92 of file cmd.py.

string cmd.Cmd.undoc_header = "Undocumented commands:" [static]

Definition at line 72 of file cmd.py.

int cmd.Cmd.use_rawinput = 1 [static]

Reimplemented in doctest._OutputRedirectingPdb, and pdb.Pdb.

Definition at line 74 of file cmd.py.


The documentation for this class was generated from the following file: