Back to index

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

List of all members.

Public Member Functions

def preloop
def postloop
def completedefault
def complete_command
def do_shell
def do_add
def help_add
def do_exit
def cmdloop
def precmd
def postcmd
def parseline
def onecmd
def emptyline
def default
def completenames
def complete
def get_names
def complete_help
def do_help
def print_topics
def columnize

Public Attributes

 lastcmd
 stdin
 stdout
 cmdqueue
 completekey
 old_completer
 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

Instance the sampleclass:
>>> mycmd = samplecmdclass()

Test for the function parseline():
>>> mycmd.parseline("")
(None, None, '')
>>> mycmd.parseline("?")
('help', '', 'help ')
>>> mycmd.parseline("?help")
('help', 'help', 'help help')
>>> mycmd.parseline("!")
('shell', '', 'shell ')
>>> mycmd.parseline("!command")
('shell', 'command', 'shell command')
>>> mycmd.parseline("func")
('func', '', 'func')
>>> mycmd.parseline("func arg1")
('func', 'arg1', 'func arg1')


Test for the function onecmd():
>>> mycmd.onecmd("")
>>> mycmd.onecmd("add 4 5")
9
>>> mycmd.onecmd("")
9
>>> mycmd.onecmd("test")
*** Unknown syntax: test

Test for the function emptyline():
>>> mycmd.emptyline()
*** Unknown syntax: test

Test for the function default():
>>> mycmd.default("default")
*** Unknown syntax: default

Test for the function completedefault():
>>> mycmd.completedefault()
This is the completedefault methode
>>> mycmd.completenames("a")
['add']

Test for the function completenames():
>>> mycmd.completenames("12")
[]
>>> mycmd.completenames("help")
['help']

Test for the function complete_help():
>>> mycmd.complete_help("a")
['add']
>>> mycmd.complete_help("he")
['help']
>>> mycmd.complete_help("12")
[]
>>> sorted(mycmd.complete_help(""))
['add', 'exit', 'help', 'shell']

Test for the function do_help():
>>> mycmd.do_help("testet")
*** No help on testet
>>> mycmd.do_help("add")
help text for add
>>> mycmd.onecmd("help add")
help text for add
>>> mycmd.do_help("")
<BLANKLINE>
Documented commands (type help <topic>):
========================================
add  help
<BLANKLINE>
Undocumented commands:
======================
exit  shell
<BLANKLINE>

Test for the function print_topics():
>>> mycmd.print_topics("header", ["command1", "command2"], 2 ,10)
header
======
command1
command2
<BLANKLINE>

Test for the function columnize():
>>> mycmd.columnize([str(i) for i in range(20)])
0  1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16  17  18  19
>>> mycmd.columnize([str(i) for i in range(20)], 10)
0  7   14
1  8   15
2  9   16
3  10  17
4  11  18
5  12  19
6  13

This is a interactive test, put some commands in the cmdqueue attribute
and let it execute
This test includes the preloop(), postloop(), default(), emptyline(),
parseline(), do_help() functions
>>> mycmd.use_rawinput=0
>>> mycmd.cmdqueue=["", "add", "add 4 5", "help", "help add","exit"]
>>> mycmd.cmdloop()
Hello from preloop
help text for add
*** invalid number of arguments
9
<BLANKLINE>
Documented commands (type help <topic>):
========================================
add  help
<BLANKLINE>
Undocumented commands:
======================
exit  shell
<BLANKLINE>
help text for add
Hello from postloop

Definition at line 15 of file test_cmd.py.


Member Function Documentation

def cmd.Cmd.cmdloop (   self,
  intro = None 
) [inherited]
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 
) [inherited]
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 
) [inherited]
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:

Definition at line 147 of file test_cmd.py.

00147 
00148     def complete_command(self):
00149         print("complete command")

def cmd.Cmd.complete_help (   self,
  args 
) [inherited]

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 test.test_cmd.samplecmdclass.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 from cmd.Cmd.

Definition at line 144 of file test_cmd.py.

00144 
00145     def completedefault(self, *ignored):
00146         print("This is the completedefault methode")

def cmd.Cmd.completenames (   self,
  text,
  ignored 
) [inherited]

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 
) [inherited]
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 test.test_cmd.samplecmdclass.do_add (   self,
  s 
)

Definition at line 153 of file test_cmd.py.

00153 
00154     def do_add(self, s):
00155         l = s.split()
00156         if len(l) != 2:
00157             print("*** invalid number of arguments")
00158             return
00159         try:
00160             l = [int(i) for i in l]
00161         except ValueError:
00162             print("*** arguments should be numbers")
00163             return
00164         print(l[0]+l[1])

def test.test_cmd.samplecmdclass.do_exit (   self,
  arg 
)

Definition at line 169 of file test_cmd.py.

00169 
00170     def do_exit(self, arg):
00171         return True
00172 

def cmd.Cmd.do_help (   self,
  arg 
) [inherited]

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 test.test_cmd.samplecmdclass.do_shell (   self,
  s 
)

Definition at line 150 of file test_cmd.py.

00150 
00151     def do_shell(self, s):
00152         pass

def cmd.Cmd.emptyline (   self) [inherited]
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) [inherited]

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:

Definition at line 165 of file test_cmd.py.

00165 
00166     def help_add(self):
00167         print("help text for add")
00168         return

def cmd.Cmd.onecmd (   self,
  line 
) [inherited]
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 
) [inherited]
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 
) [inherited]
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

Hook method executed once when the cmdloop() method is about to
return.

Reimplemented from cmd.Cmd.

Definition at line 141 of file test_cmd.py.

00141 
00142     def postloop(self):
00143         print("Hello from postloop")

def cmd.Cmd.precmd (   self,
  line 
) [inherited]
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

Hook method executed once when the cmdloop() method is called.

Reimplemented from cmd.Cmd.

Definition at line 138 of file test_cmd.py.

00138 
00139     def preloop(self):
00140         print("Hello from preloop")

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

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

cmd.Cmd.cmdqueue [inherited]

Reimplemented in pdb.Pdb.

Definition at line 95 of file cmd.py.

cmd.Cmd.completekey [inherited]

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, inherited]

Definition at line 70 of file cmd.py.

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

Definition at line 69 of file cmd.py.

cmd.Cmd.identchars = IDENTCHARS [static, inherited]

Definition at line 65 of file cmd.py.

cmd.Cmd.intro = None [static, inherited]

Definition at line 68 of file cmd.py.

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

Reimplemented in pdb.Pdb.

Definition at line 67 of file cmd.py.

cmd.Cmd.lastcmd [inherited]

Reimplemented in pdb.Pdb.

Definition at line 207 of file cmd.py.

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

Definition at line 71 of file cmd.py.

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

Definition at line 73 of file cmd.py.

cmd.Cmd.old_completer [inherited]

Definition at line 109 of file cmd.py.

cmd.Cmd.prompt = PROMPT [static, inherited]

Reimplemented in pstats.ProfileBrowser, and pdb.Pdb.

Definition at line 64 of file cmd.py.

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

Definition at line 66 of file cmd.py.

cmd.Cmd.stdin [inherited]

Definition at line 88 of file cmd.py.

cmd.Cmd.stdout [inherited]

Definition at line 92 of file cmd.py.

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

Definition at line 72 of file cmd.py.

int cmd.Cmd.use_rawinput = 1 [static, inherited]

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: