Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python2....
File: cmd.py
"""A generic class to build line-oriented command interpreters.
[0] Fix | Delete
[1] Fix | Delete
Interpreters constructed with this class obey the following conventions:
[2] Fix | Delete
[3] Fix | Delete
1. End of file on input is processed as the command 'EOF'.
[4] Fix | Delete
2. A command is parsed out of each line by collecting the prefix composed
[5] Fix | Delete
of characters in the identchars member.
[6] Fix | Delete
3. A command `foo' is dispatched to a method 'do_foo()'; the do_ method
[7] Fix | Delete
is passed a single argument consisting of the remainder of the line.
[8] Fix | Delete
4. Typing an empty line repeats the last command. (Actually, it calls the
[9] Fix | Delete
method `emptyline', which may be overridden in a subclass.)
[10] Fix | Delete
5. There is a predefined `help' method. Given an argument `topic', it
[11] Fix | Delete
calls the command `help_topic'. With no arguments, it lists all topics
[12] Fix | Delete
with defined help_ functions, broken into up to three topics; documented
[13] Fix | Delete
commands, miscellaneous help topics, and undocumented commands.
[14] Fix | Delete
6. The command '?' is a synonym for `help'. The command '!' is a synonym
[15] Fix | Delete
for `shell', if a do_shell method exists.
[16] Fix | Delete
7. If completion is enabled, completing commands will be done automatically,
[17] Fix | Delete
and completing of commands args is done by calling complete_foo() with
[18] Fix | Delete
arguments text, line, begidx, endidx. text is string we are matching
[19] Fix | Delete
against, all returned matches must begin with it. line is the current
[20] Fix | Delete
input line (lstripped), begidx and endidx are the beginning and end
[21] Fix | Delete
indexes of the text being matched, which could be used to provide
[22] Fix | Delete
different completion depending upon which position the argument is in.
[23] Fix | Delete
[24] Fix | Delete
The `default' method may be overridden to intercept commands for which there
[25] Fix | Delete
is no do_ method.
[26] Fix | Delete
[27] Fix | Delete
The `completedefault' method may be overridden to intercept completions for
[28] Fix | Delete
commands that have no complete_ method.
[29] Fix | Delete
[30] Fix | Delete
The data member `self.ruler' sets the character used to draw separator lines
[31] Fix | Delete
in the help messages. If empty, no ruler line is drawn. It defaults to "=".
[32] Fix | Delete
[33] Fix | Delete
If the value of `self.intro' is nonempty when the cmdloop method is called,
[34] Fix | Delete
it is printed out on interpreter startup. This value may be overridden
[35] Fix | Delete
via an optional argument to the cmdloop() method.
[36] Fix | Delete
[37] Fix | Delete
The data members `self.doc_header', `self.misc_header', and
[38] Fix | Delete
`self.undoc_header' set the headers used for the help function's
[39] Fix | Delete
listings of documented functions, miscellaneous topics, and undocumented
[40] Fix | Delete
functions respectively.
[41] Fix | Delete
[42] Fix | Delete
These interpreters use raw_input; thus, if the readline module is loaded,
[43] Fix | Delete
they automatically support Emacs-like command history and editing features.
[44] Fix | Delete
"""
[45] Fix | Delete
[46] Fix | Delete
import string
[47] Fix | Delete
[48] Fix | Delete
__all__ = ["Cmd"]
[49] Fix | Delete
[50] Fix | Delete
PROMPT = '(Cmd) '
[51] Fix | Delete
IDENTCHARS = string.ascii_letters + string.digits + '_'
[52] Fix | Delete
[53] Fix | Delete
class Cmd:
[54] Fix | Delete
"""A simple framework for writing line-oriented command interpreters.
[55] Fix | Delete
[56] Fix | Delete
These are often useful for test harnesses, administrative tools, and
[57] Fix | Delete
prototypes that will later be wrapped in a more sophisticated interface.
[58] Fix | Delete
[59] Fix | Delete
A Cmd instance or subclass instance is a line-oriented interpreter
[60] Fix | Delete
framework. There is no good reason to instantiate Cmd itself; rather,
[61] Fix | Delete
it's useful as a superclass of an interpreter class you define yourself
[62] Fix | Delete
in order to inherit Cmd's methods and encapsulate action methods.
[63] Fix | Delete
[64] Fix | Delete
"""
[65] Fix | Delete
prompt = PROMPT
[66] Fix | Delete
identchars = IDENTCHARS
[67] Fix | Delete
ruler = '='
[68] Fix | Delete
lastcmd = ''
[69] Fix | Delete
intro = None
[70] Fix | Delete
doc_leader = ""
[71] Fix | Delete
doc_header = "Documented commands (type help <topic>):"
[72] Fix | Delete
misc_header = "Miscellaneous help topics:"
[73] Fix | Delete
undoc_header = "Undocumented commands:"
[74] Fix | Delete
nohelp = "*** No help on %s"
[75] Fix | Delete
use_rawinput = 1
[76] Fix | Delete
[77] Fix | Delete
def __init__(self, completekey='tab', stdin=None, stdout=None):
[78] Fix | Delete
"""Instantiate a line-oriented interpreter framework.
[79] Fix | Delete
[80] Fix | Delete
The optional argument 'completekey' is the readline name of a
[81] Fix | Delete
completion key; it defaults to the Tab key. If completekey is
[82] Fix | Delete
not None and the readline module is available, command completion
[83] Fix | Delete
is done automatically. The optional arguments stdin and stdout
[84] Fix | Delete
specify alternate input and output file objects; if not specified,
[85] Fix | Delete
sys.stdin and sys.stdout are used.
[86] Fix | Delete
[87] Fix | Delete
"""
[88] Fix | Delete
import sys
[89] Fix | Delete
if stdin is not None:
[90] Fix | Delete
self.stdin = stdin
[91] Fix | Delete
else:
[92] Fix | Delete
self.stdin = sys.stdin
[93] Fix | Delete
if stdout is not None:
[94] Fix | Delete
self.stdout = stdout
[95] Fix | Delete
else:
[96] Fix | Delete
self.stdout = sys.stdout
[97] Fix | Delete
self.cmdqueue = []
[98] Fix | Delete
self.completekey = completekey
[99] Fix | Delete
[100] Fix | Delete
def cmdloop(self, intro=None):
[101] Fix | Delete
"""Repeatedly issue a prompt, accept input, parse an initial prefix
[102] Fix | Delete
off the received input, and dispatch to action methods, passing them
[103] Fix | Delete
the remainder of the line as argument.
[104] Fix | Delete
[105] Fix | Delete
"""
[106] Fix | Delete
[107] Fix | Delete
self.preloop()
[108] Fix | Delete
if self.use_rawinput and self.completekey:
[109] Fix | Delete
try:
[110] Fix | Delete
import readline
[111] Fix | Delete
self.old_completer = readline.get_completer()
[112] Fix | Delete
readline.set_completer(self.complete)
[113] Fix | Delete
readline.parse_and_bind(self.completekey+": complete")
[114] Fix | Delete
except ImportError:
[115] Fix | Delete
pass
[116] Fix | Delete
try:
[117] Fix | Delete
if intro is not None:
[118] Fix | Delete
self.intro = intro
[119] Fix | Delete
if self.intro:
[120] Fix | Delete
self.stdout.write(str(self.intro)+"\n")
[121] Fix | Delete
stop = None
[122] Fix | Delete
while not stop:
[123] Fix | Delete
if self.cmdqueue:
[124] Fix | Delete
line = self.cmdqueue.pop(0)
[125] Fix | Delete
else:
[126] Fix | Delete
if self.use_rawinput:
[127] Fix | Delete
try:
[128] Fix | Delete
line = raw_input(self.prompt)
[129] Fix | Delete
except EOFError:
[130] Fix | Delete
line = 'EOF'
[131] Fix | Delete
else:
[132] Fix | Delete
self.stdout.write(self.prompt)
[133] Fix | Delete
self.stdout.flush()
[134] Fix | Delete
line = self.stdin.readline()
[135] Fix | Delete
if not len(line):
[136] Fix | Delete
line = 'EOF'
[137] Fix | Delete
else:
[138] Fix | Delete
line = line.rstrip('\r\n')
[139] Fix | Delete
line = self.precmd(line)
[140] Fix | Delete
stop = self.onecmd(line)
[141] Fix | Delete
stop = self.postcmd(stop, line)
[142] Fix | Delete
self.postloop()
[143] Fix | Delete
finally:
[144] Fix | Delete
if self.use_rawinput and self.completekey:
[145] Fix | Delete
try:
[146] Fix | Delete
import readline
[147] Fix | Delete
readline.set_completer(self.old_completer)
[148] Fix | Delete
except ImportError:
[149] Fix | Delete
pass
[150] Fix | Delete
[151] Fix | Delete
[152] Fix | Delete
def precmd(self, line):
[153] Fix | Delete
"""Hook method executed just before the command line is
[154] Fix | Delete
interpreted, but after the input prompt is generated and issued.
[155] Fix | Delete
[156] Fix | Delete
"""
[157] Fix | Delete
return line
[158] Fix | Delete
[159] Fix | Delete
def postcmd(self, stop, line):
[160] Fix | Delete
"""Hook method executed just after a command dispatch is finished."""
[161] Fix | Delete
return stop
[162] Fix | Delete
[163] Fix | Delete
def preloop(self):
[164] Fix | Delete
"""Hook method executed once when the cmdloop() method is called."""
[165] Fix | Delete
pass
[166] Fix | Delete
[167] Fix | Delete
def postloop(self):
[168] Fix | Delete
"""Hook method executed once when the cmdloop() method is about to
[169] Fix | Delete
return.
[170] Fix | Delete
[171] Fix | Delete
"""
[172] Fix | Delete
pass
[173] Fix | Delete
[174] Fix | Delete
def parseline(self, line):
[175] Fix | Delete
"""Parse the line into a command name and a string containing
[176] Fix | Delete
the arguments. Returns a tuple containing (command, args, line).
[177] Fix | Delete
'command' and 'args' may be None if the line couldn't be parsed.
[178] Fix | Delete
"""
[179] Fix | Delete
line = line.strip()
[180] Fix | Delete
if not line:
[181] Fix | Delete
return None, None, line
[182] Fix | Delete
elif line[0] == '?':
[183] Fix | Delete
line = 'help ' + line[1:]
[184] Fix | Delete
elif line[0] == '!':
[185] Fix | Delete
if hasattr(self, 'do_shell'):
[186] Fix | Delete
line = 'shell ' + line[1:]
[187] Fix | Delete
else:
[188] Fix | Delete
return None, None, line
[189] Fix | Delete
i, n = 0, len(line)
[190] Fix | Delete
while i < n and line[i] in self.identchars: i = i+1
[191] Fix | Delete
cmd, arg = line[:i], line[i:].strip()
[192] Fix | Delete
return cmd, arg, line
[193] Fix | Delete
[194] Fix | Delete
def onecmd(self, line):
[195] Fix | Delete
"""Interpret the argument as though it had been typed in response
[196] Fix | Delete
to the prompt.
[197] Fix | Delete
[198] Fix | Delete
This may be overridden, but should not normally need to be;
[199] Fix | Delete
see the precmd() and postcmd() methods for useful execution hooks.
[200] Fix | Delete
The return value is a flag indicating whether interpretation of
[201] Fix | Delete
commands by the interpreter should stop.
[202] Fix | Delete
[203] Fix | Delete
"""
[204] Fix | Delete
cmd, arg, line = self.parseline(line)
[205] Fix | Delete
if not line:
[206] Fix | Delete
return self.emptyline()
[207] Fix | Delete
if cmd is None:
[208] Fix | Delete
return self.default(line)
[209] Fix | Delete
self.lastcmd = line
[210] Fix | Delete
if line == 'EOF' :
[211] Fix | Delete
self.lastcmd = ''
[212] Fix | Delete
if cmd == '':
[213] Fix | Delete
return self.default(line)
[214] Fix | Delete
else:
[215] Fix | Delete
try:
[216] Fix | Delete
func = getattr(self, 'do_' + cmd)
[217] Fix | Delete
except AttributeError:
[218] Fix | Delete
return self.default(line)
[219] Fix | Delete
return func(arg)
[220] Fix | Delete
[221] Fix | Delete
def emptyline(self):
[222] Fix | Delete
"""Called when an empty line is entered in response to the prompt.
[223] Fix | Delete
[224] Fix | Delete
If this method is not overridden, it repeats the last nonempty
[225] Fix | Delete
command entered.
[226] Fix | Delete
[227] Fix | Delete
"""
[228] Fix | Delete
if self.lastcmd:
[229] Fix | Delete
return self.onecmd(self.lastcmd)
[230] Fix | Delete
[231] Fix | Delete
def default(self, line):
[232] Fix | Delete
"""Called on an input line when the command prefix is not recognized.
[233] Fix | Delete
[234] Fix | Delete
If this method is not overridden, it prints an error message and
[235] Fix | Delete
returns.
[236] Fix | Delete
[237] Fix | Delete
"""
[238] Fix | Delete
self.stdout.write('*** Unknown syntax: %s\n'%line)
[239] Fix | Delete
[240] Fix | Delete
def completedefault(self, *ignored):
[241] Fix | Delete
"""Method called to complete an input line when no command-specific
[242] Fix | Delete
complete_*() method is available.
[243] Fix | Delete
[244] Fix | Delete
By default, it returns an empty list.
[245] Fix | Delete
[246] Fix | Delete
"""
[247] Fix | Delete
return []
[248] Fix | Delete
[249] Fix | Delete
def completenames(self, text, *ignored):
[250] Fix | Delete
dotext = 'do_'+text
[251] Fix | Delete
return [a[3:] for a in self.get_names() if a.startswith(dotext)]
[252] Fix | Delete
[253] Fix | Delete
def complete(self, text, state):
[254] Fix | Delete
"""Return the next possible completion for 'text'.
[255] Fix | Delete
[256] Fix | Delete
If a command has not been entered, then complete against command list.
[257] Fix | Delete
Otherwise try to call complete_<command> to get list of completions.
[258] Fix | Delete
"""
[259] Fix | Delete
if state == 0:
[260] Fix | Delete
import readline
[261] Fix | Delete
origline = readline.get_line_buffer()
[262] Fix | Delete
line = origline.lstrip()
[263] Fix | Delete
stripped = len(origline) - len(line)
[264] Fix | Delete
begidx = readline.get_begidx() - stripped
[265] Fix | Delete
endidx = readline.get_endidx() - stripped
[266] Fix | Delete
if begidx>0:
[267] Fix | Delete
cmd, args, foo = self.parseline(line)
[268] Fix | Delete
if cmd == '':
[269] Fix | Delete
compfunc = self.completedefault
[270] Fix | Delete
else:
[271] Fix | Delete
try:
[272] Fix | Delete
compfunc = getattr(self, 'complete_' + cmd)
[273] Fix | Delete
except AttributeError:
[274] Fix | Delete
compfunc = self.completedefault
[275] Fix | Delete
else:
[276] Fix | Delete
compfunc = self.completenames
[277] Fix | Delete
self.completion_matches = compfunc(text, line, begidx, endidx)
[278] Fix | Delete
try:
[279] Fix | Delete
return self.completion_matches[state]
[280] Fix | Delete
except IndexError:
[281] Fix | Delete
return None
[282] Fix | Delete
[283] Fix | Delete
def get_names(self):
[284] Fix | Delete
# This method used to pull in base class attributes
[285] Fix | Delete
# at a time dir() didn't do it yet.
[286] Fix | Delete
return dir(self.__class__)
[287] Fix | Delete
[288] Fix | Delete
def complete_help(self, *args):
[289] Fix | Delete
commands = set(self.completenames(*args))
[290] Fix | Delete
topics = set(a[5:] for a in self.get_names()
[291] Fix | Delete
if a.startswith('help_' + args[0]))
[292] Fix | Delete
return list(commands | topics)
[293] Fix | Delete
[294] Fix | Delete
def do_help(self, arg):
[295] Fix | Delete
'List available commands with "help" or detailed help with "help cmd".'
[296] Fix | Delete
if arg:
[297] Fix | Delete
# XXX check arg syntax
[298] Fix | Delete
try:
[299] Fix | Delete
func = getattr(self, 'help_' + arg)
[300] Fix | Delete
except AttributeError:
[301] Fix | Delete
try:
[302] Fix | Delete
doc=getattr(self, 'do_' + arg).__doc__
[303] Fix | Delete
if doc:
[304] Fix | Delete
self.stdout.write("%s\n"%str(doc))
[305] Fix | Delete
return
[306] Fix | Delete
except AttributeError:
[307] Fix | Delete
pass
[308] Fix | Delete
self.stdout.write("%s\n"%str(self.nohelp % (arg,)))
[309] Fix | Delete
return
[310] Fix | Delete
func()
[311] Fix | Delete
else:
[312] Fix | Delete
names = self.get_names()
[313] Fix | Delete
cmds_doc = []
[314] Fix | Delete
cmds_undoc = []
[315] Fix | Delete
help = {}
[316] Fix | Delete
for name in names:
[317] Fix | Delete
if name[:5] == 'help_':
[318] Fix | Delete
help[name[5:]]=1
[319] Fix | Delete
names.sort()
[320] Fix | Delete
# There can be duplicates if routines overridden
[321] Fix | Delete
prevname = ''
[322] Fix | Delete
for name in names:
[323] Fix | Delete
if name[:3] == 'do_':
[324] Fix | Delete
if name == prevname:
[325] Fix | Delete
continue
[326] Fix | Delete
prevname = name
[327] Fix | Delete
cmd=name[3:]
[328] Fix | Delete
if cmd in help:
[329] Fix | Delete
cmds_doc.append(cmd)
[330] Fix | Delete
del help[cmd]
[331] Fix | Delete
elif getattr(self, name).__doc__:
[332] Fix | Delete
cmds_doc.append(cmd)
[333] Fix | Delete
else:
[334] Fix | Delete
cmds_undoc.append(cmd)
[335] Fix | Delete
self.stdout.write("%s\n"%str(self.doc_leader))
[336] Fix | Delete
self.print_topics(self.doc_header, cmds_doc, 15,80)
[337] Fix | Delete
self.print_topics(self.misc_header, help.keys(),15,80)
[338] Fix | Delete
self.print_topics(self.undoc_header, cmds_undoc, 15,80)
[339] Fix | Delete
[340] Fix | Delete
def print_topics(self, header, cmds, cmdlen, maxcol):
[341] Fix | Delete
if cmds:
[342] Fix | Delete
self.stdout.write("%s\n"%str(header))
[343] Fix | Delete
if self.ruler:
[344] Fix | Delete
self.stdout.write("%s\n"%str(self.ruler * len(header)))
[345] Fix | Delete
self.columnize(cmds, maxcol-1)
[346] Fix | Delete
self.stdout.write("\n")
[347] Fix | Delete
[348] Fix | Delete
def columnize(self, list, displaywidth=80):
[349] Fix | Delete
"""Display a list of strings as a compact set of columns.
[350] Fix | Delete
[351] Fix | Delete
Each column is only as wide as necessary.
[352] Fix | Delete
Columns are separated by two spaces (one was not legible enough).
[353] Fix | Delete
"""
[354] Fix | Delete
if not list:
[355] Fix | Delete
self.stdout.write("<empty>\n")
[356] Fix | Delete
return
[357] Fix | Delete
nonstrings = [i for i in range(len(list))
[358] Fix | Delete
if not isinstance(list[i], str)]
[359] Fix | Delete
if nonstrings:
[360] Fix | Delete
raise TypeError, ("list[i] not a string for i in %s" %
[361] Fix | Delete
", ".join(map(str, nonstrings)))
[362] Fix | Delete
size = len(list)
[363] Fix | Delete
if size == 1:
[364] Fix | Delete
self.stdout.write('%s\n'%str(list[0]))
[365] Fix | Delete
return
[366] Fix | Delete
# Try every row count from 1 upwards
[367] Fix | Delete
for nrows in range(1, len(list)):
[368] Fix | Delete
ncols = (size+nrows-1) // nrows
[369] Fix | Delete
colwidths = []
[370] Fix | Delete
totwidth = -2
[371] Fix | Delete
for col in range(ncols):
[372] Fix | Delete
colwidth = 0
[373] Fix | Delete
for row in range(nrows):
[374] Fix | Delete
i = row + nrows*col
[375] Fix | Delete
if i >= size:
[376] Fix | Delete
break
[377] Fix | Delete
x = list[i]
[378] Fix | Delete
colwidth = max(colwidth, len(x))
[379] Fix | Delete
colwidths.append(colwidth)
[380] Fix | Delete
totwidth += colwidth + 2
[381] Fix | Delete
if totwidth > displaywidth:
[382] Fix | Delete
break
[383] Fix | Delete
if totwidth <= displaywidth:
[384] Fix | Delete
break
[385] Fix | Delete
else:
[386] Fix | Delete
nrows = len(list)
[387] Fix | Delete
ncols = 1
[388] Fix | Delete
colwidths = [0]
[389] Fix | Delete
for row in range(nrows):
[390] Fix | Delete
texts = []
[391] Fix | Delete
for col in range(ncols):
[392] Fix | Delete
i = row + nrows*col
[393] Fix | Delete
if i >= size:
[394] Fix | Delete
x = ""
[395] Fix | Delete
else:
[396] Fix | Delete
x = list[i]
[397] Fix | Delete
texts.append(x)
[398] Fix | Delete
while texts and not texts[-1]:
[399] Fix | Delete
del texts[-1]
[400] Fix | Delete
for col in range(len(texts)):
[401] Fix | Delete
texts[col] = texts[col].ljust(colwidths[col])
[402] Fix | Delete
self.stdout.write("%s\n"%str(" ".join(texts)))
[403] Fix | Delete
[404] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function