230
|
1 """Variant on standard library's cmd with extra features.
|
|
2
|
|
3 To use, simply import cmd2.Cmd instead of cmd.Cmd; use precisely as though you
|
|
4 were using the standard library's cmd, while enjoying the extra features.
|
|
5
|
|
6 Searchable command history (commands: "hi", "li", "run")
|
|
7 Load commands from file, save to file, edit commands in file
|
|
8 Multi-line commands
|
|
9 Case-insensitive commands
|
|
10 Special-character shortcut commands (beyond cmd's "@" and "!")
|
|
11 Settable environment parameters
|
|
12 Optional _onchange_{paramname} called when environment parameter changes
|
|
13 Parsing commands with `optparse` options (flags)
|
|
14 Redirection to file with >, >>; input from file with <
|
|
15 Easy transcript-based testing of applications (see example/example.py)
|
|
16
|
|
17 Note that redirection with > and | will only work if `self.stdout.write()`
|
|
18 is used in place of `print`. The standard library's `cmd` module is
|
|
19 written to use `self.stdout.write()`,
|
|
20
|
|
21 - Catherine Devlin, Jan 03 2008 - catherinedevlin.blogspot.com
|
|
22
|
|
23 mercurial repository at http://www.assembla.com/wiki/show/python-cmd2
|
|
24 CHANGES:
|
|
25 As of 0.3.0, options should be specified as `optparse` options. See README.txt.
|
|
26 flagReader.py options are still supported for backward compatibility
|
|
27 """
|
|
28 import cmd, re, os, sys, optparse, subprocess, tempfile, pyparsing, doctest
|
|
29 import unittest, string, datetime, urllib, inspect
|
|
30 from optparse import make_option
|
|
31 __version__ = '0.4.8'
|
|
32
|
|
33 class OptionParser(optparse.OptionParser):
|
|
34 def exit(self, status=0, msg=None):
|
|
35 self.values._exit = True
|
|
36 if msg:
|
|
37 print msg
|
|
38
|
|
39 def print_help(self, *args, **kwargs):
|
|
40 # now, I need to call help of the calling function. Hmm.
|
|
41 try:
|
|
42 print self._func.__doc__
|
|
43 except AttributeError:
|
|
44 pass
|
|
45 optparse.OptionParser.print_help(self, *args, **kwargs)
|
|
46
|
|
47 def error(self, msg):
|
|
48 """error(msg : string)
|
|
49
|
|
50 Print a usage message incorporating 'msg' to stderr and exit.
|
|
51 If you override this in a subclass, it should not return -- it
|
|
52 should either exit or raise an exception.
|
|
53 """
|
|
54 raise
|
|
55
|
|
56 def remainingArgs(oldArgs, newArgList):
|
|
57 '''
|
|
58 >>> remainingArgs('-f bar bar cow', ['bar', 'cow'])
|
|
59 'bar cow'
|
|
60 '''
|
|
61 pattern = '\s+'.join(re.escape(a) for a in newArgList) + '\s*$'
|
|
62 matchObj = re.search(pattern, oldArgs)
|
|
63 return oldArgs[matchObj.start():]
|
|
64
|
|
65 def options(option_list):
|
|
66 def option_setup(func):
|
|
67 optionParser = OptionParser()
|
|
68 for opt in option_list:
|
|
69 optionParser.add_option(opt)
|
|
70 optionParser.set_usage("%s [options] arg" % func.__name__.strip('do_'))
|
|
71 optionParser._func = func
|
|
72 def newFunc(instance, arg):
|
|
73 try:
|
|
74 opts, newArgList = optionParser.parse_args(arg.split()) # doesn't understand quoted strings shouldn't be dissected!
|
|
75 newArgs = remainingArgs(arg, newArgList) # should it permit flags after args?
|
|
76 except (optparse.OptionValueError, optparse.BadOptionError,
|
|
77 optparse.OptionError, optparse.AmbiguousOptionError,
|
|
78 optparse.OptionConflictError), e:
|
|
79 print e
|
|
80 optionParser.print_help()
|
|
81 return
|
|
82 if hasattr(opts, '_exit'):
|
|
83 return None
|
|
84 if hasattr(arg, 'parser'):
|
|
85 terminator = arg.parsed.terminator
|
|
86 try:
|
|
87 if arg.parsed.terminator[0] == '\n':
|
|
88 terminator = arg.parsed.terminator[0]
|
|
89 except IndexError:
|
|
90 pass
|
|
91 arg = arg.parser('%s %s%s%s' % (arg.parsed.command, newArgs,
|
|
92 terminator, arg.parsed.suffix))
|
|
93 else:
|
|
94 arg = newArgs
|
|
95 result = func(instance, arg, opts)
|
|
96 return result
|
|
97 newFunc.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help())
|
|
98 return newFunc
|
|
99 return option_setup
|
|
100
|
|
101 class PasteBufferError(EnvironmentError):
|
|
102 if sys.platform[:3] == 'win':
|
|
103 errmsg = """Redirecting to or from paste buffer requires pywin32
|
|
104 to be installed on operating system.
|
|
105 Download from http://sourceforge.net/projects/pywin32/"""
|
|
106 else:
|
|
107 errmsg = """Redirecting to or from paste buffer requires xclip
|
|
108 to be installed on operating system.
|
|
109 On Debian/Ubuntu, 'sudo apt-get install xclip' will install it."""
|
|
110 def __init__(self):
|
|
111 Exception.__init__(self, self.errmsg)
|
|
112
|
|
113 '''check here if functions exist; otherwise, stub out'''
|
|
114 pastebufferr = """Redirecting to or from paste buffer requires %s
|
|
115 to be installed on operating system.
|
|
116 %s"""
|
|
117 if subprocess.mswindows:
|
|
118 try:
|
|
119 import win32clipboard
|
|
120 def getPasteBuffer():
|
|
121 win32clipboard.OpenClipboard(0)
|
|
122 try:
|
|
123 result = win32clipboard.GetClipboardData()
|
|
124 except TypeError:
|
|
125 result = '' #non-text
|
|
126 win32clipboard.CloseClipboard()
|
|
127 return result
|
|
128 def writeToPasteBuffer(txt):
|
|
129 win32clipboard.OpenClipboard(0)
|
|
130 win32clipboard.EmptyClipboard()
|
|
131 win32clipboard.SetClipboardText(txt)
|
|
132 win32clipboard.CloseClipboard()
|
|
133 except ImportError:
|
|
134 def getPasteBuffer(*args):
|
|
135 raise OSError, pastebufferr % ('pywin32', 'Download from http://sourceforge.net/projects/pywin32/')
|
|
136 setPasteBuffer = getPasteBuffer
|
|
137 else:
|
|
138 can_clip = False
|
|
139 try:
|
|
140 subprocess.check_call('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
|
|
141 can_clip = True
|
|
142 except AttributeError: # check_call not defined, Python < 2.5
|
|
143 teststring = 'Testing for presence of xclip.'
|
|
144 xclipproc = subprocess.Popen('xclip -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
|
|
145 xclipproc.stdin.write(teststring)
|
|
146 xclipproc.stdin.close()
|
|
147 xclipproc = subprocess.Popen('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
|
|
148 if xclipproc.stdout.read() == teststring:
|
|
149 can_clip = True
|
|
150 except (subprocess.CalledProcessError, OSError, IOError):
|
|
151 pass
|
|
152 if can_clip:
|
|
153 def getPasteBuffer():
|
|
154 xclipproc = subprocess.Popen('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
|
|
155 return xclipproc.stdout.read()
|
|
156 def writeToPasteBuffer(txt):
|
|
157 xclipproc = subprocess.Popen('xclip -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
|
|
158 xclipproc.stdin.write(txt)
|
|
159 xclipproc.stdin.close()
|
|
160 # but we want it in both the "primary" and "mouse" clipboards
|
|
161 xclipproc = subprocess.Popen('xclip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
|
|
162 xclipproc.stdin.write(txt)
|
|
163 xclipproc.stdin.close()
|
|
164 else:
|
|
165 def getPasteBuffer(*args):
|
|
166 raise OSError, pastebufferr % ('xclip', 'On Debian/Ubuntu, install with "sudo apt-get install xclip"')
|
|
167 setPasteBuffer = getPasteBuffer
|
|
168 writeToPasteBuffer = getPasteBuffer
|
|
169
|
|
170 pyparsing.ParserElement.setDefaultWhitespaceChars(' \t')
|
|
171
|
|
172 class ParsedString(str):
|
|
173 pass
|
|
174
|
|
175 class SkipToLast(pyparsing.SkipTo):
|
|
176 def parseImpl( self, instring, loc, doActions=True ):
|
|
177 resultStore = []
|
|
178 startLoc = loc
|
|
179 instrlen = len(instring)
|
|
180 expr = self.expr
|
|
181 failParse = False
|
|
182 while loc <= instrlen:
|
|
183 try:
|
|
184 if self.failOn:
|
|
185 failParse = True
|
|
186 self.failOn.tryParse(instring, loc)
|
|
187 failParse = False
|
|
188 loc = expr._skipIgnorables( instring, loc )
|
|
189 expr._parse( instring, loc, doActions=False, callPreParse=False )
|
|
190 skipText = instring[startLoc:loc]
|
|
191 if self.includeMatch:
|
|
192 loc,mat = expr._parse(instring,loc,doActions,callPreParse=False)
|
|
193 if mat:
|
|
194 skipRes = ParseResults( skipText )
|
|
195 skipRes += mat
|
|
196 resultStore.append((loc, [ skipRes ]))
|
|
197 else:
|
|
198 resultStore,append((loc, [ skipText ]))
|
|
199 else:
|
|
200 resultStore.append((loc, [ skipText ]))
|
|
201 loc += 1
|
|
202 except (pyparsing.ParseException,IndexError):
|
|
203 if failParse:
|
|
204 raise
|
|
205 else:
|
|
206 loc += 1
|
|
207 if resultStore:
|
|
208 return resultStore[-1]
|
|
209 else:
|
|
210 exc = self.myException
|
|
211 exc.loc = loc
|
|
212 exc.pstr = instring
|
|
213 raise exc
|
|
214
|
|
215 def replace_with_file_contents(fname):
|
|
216 if fname:
|
|
217 try:
|
|
218 result = open(os.path.expanduser(fname[0])).read()
|
|
219 except IOError:
|
|
220 result = '< %s' % fname[0] # wasn't a file after all
|
|
221 else:
|
|
222 result = getPasteBuffer()
|
|
223 return result
|
|
224
|
|
225 class Cmd(cmd.Cmd):
|
|
226 echo = False
|
|
227 case_insensitive = True
|
|
228 continuation_prompt = '> '
|
|
229 timing = False
|
|
230 legalChars = '!#$%.:?@_' + pyparsing.alphanums + pyparsing.alphas8bit # make sure your terminators are not in here!
|
|
231 shortcuts = {'?': 'help', '!': 'shell', '@': 'load' }
|
|
232 excludeFromHistory = '''run r list l history hi ed edit li eof'''.split()
|
|
233 noSpecialParse = 'set ed edit exit'.split()
|
|
234 defaultExtension = 'txt'
|
|
235 default_file_name = 'command.txt'
|
|
236 abbrev = True
|
|
237 settable = ['prompt', 'continuation_prompt', 'default_file_name', 'editor',
|
|
238 'case_insensitive', 'echo', 'timing', 'abbrev']
|
|
239 settable.sort()
|
|
240
|
|
241 editor = os.environ.get('EDITOR')
|
|
242 _STOP_AND_EXIT = 2
|
|
243 if not editor:
|
|
244 if sys.platform[:3] == 'win':
|
|
245 editor = 'notepad'
|
|
246 else:
|
|
247 for editor in ['gedit', 'kate', 'vim', 'emacs', 'nano', 'pico']:
|
|
248 if not os.system('which %s' % (editor)):
|
|
249 break
|
|
250
|
|
251 def do_cmdenvironment(self, args):
|
|
252 '''Summary report of interactive parameters.'''
|
|
253 self.stdout.write("""
|
|
254 Commands are %(casesensitive)scase-sensitive.
|
|
255 Commands may be terminated with: %(terminators)s
|
|
256 Settable parameters: %(settable)s
|
|
257 """ %
|
|
258 { 'casesensitive': (self.case_insensitive and 'not ') or '',
|
|
259 'terminators': str(self.terminators),
|
|
260 'settable': ' '.join(self.settable)
|
|
261 })
|
|
262
|
|
263 def do_help(self, arg):
|
|
264 try:
|
|
265 fn = getattr(self, 'do_' + arg)
|
|
266 if fn and fn.optionParser:
|
|
267 fn.optionParser.print_help(file=self.stdout)
|
|
268 return
|
|
269 except AttributeError:
|
|
270 pass
|
|
271 cmd.Cmd.do_help(self, arg)
|
|
272
|
|
273 def __init__(self, *args, **kwargs):
|
|
274 cmd.Cmd.__init__(self, *args, **kwargs)
|
|
275 self.history = History()
|
|
276 self._init_parser()
|
|
277 self.pystate = {}
|
|
278
|
|
279 def do_shortcuts(self, args):
|
|
280 """Lists single-key shortcuts available."""
|
|
281 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in self.shortcuts.items())
|
|
282 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result))
|
|
283
|
|
284 prefixParser = pyparsing.Empty()
|
|
285 commentGrammars = pyparsing.Or([pyparsing.pythonStyleComment, pyparsing.cStyleComment])
|
|
286 commentGrammars.addParseAction(lambda x: '')
|
|
287 commentInProgress = ((pyparsing.White() | pyparsing.lineStart) +
|
|
288 pyparsing.Literal('/*') + pyparsing.SkipTo(pyparsing.stringEnd))
|
|
289 # `blah/*` means `everything in directory `blah`, not comment
|
|
290 terminators = [';']
|
|
291 blankLinesAllowed = False
|
|
292 multilineCommands = []
|
|
293
|
|
294 def _init_parser(self):
|
|
295 r'''
|
|
296 >>> c = Cmd()
|
|
297 >>> c.multilineCommands = ['multiline']
|
|
298 >>> c.case_insensitive = True
|
|
299 >>> c._init_parser()
|
|
300 >>> print c.parser.parseString('').dump()
|
|
301 []
|
|
302 >>> print c.parser.parseString('/* empty command */').dump()
|
|
303 []
|
|
304 >>> print c.parser.parseString('plainword').dump()
|
|
305 ['plainword', '']
|
|
306 - command: plainword
|
|
307 - statement: ['plainword', '']
|
|
308 - command: plainword
|
|
309 >>> print c.parser.parseString('termbare;').dump()
|
|
310 ['termbare', '', ';', '']
|
|
311 - command: termbare
|
|
312 - statement: ['termbare', '', ';']
|
|
313 - command: termbare
|
|
314 - terminator: ;
|
|
315 - terminator: ;
|
|
316 >>> print c.parser.parseString('termbare; suffx').dump()
|
|
317 ['termbare', '', ';', 'suffx']
|
|
318 - command: termbare
|
|
319 - statement: ['termbare', '', ';']
|
|
320 - command: termbare
|
|
321 - terminator: ;
|
|
322 - suffix: suffx
|
|
323 - terminator: ;
|
|
324 >>> print c.parser.parseString('barecommand').dump()
|
|
325 ['barecommand', '']
|
|
326 - command: barecommand
|
|
327 - statement: ['barecommand', '']
|
|
328 - command: barecommand
|
|
329 >>> print c.parser.parseString('COMmand with args').dump()
|
|
330 ['command', 'with args']
|
|
331 - args: with args
|
|
332 - command: command
|
|
333 - statement: ['command', 'with args']
|
|
334 - args: with args
|
|
335 - command: command
|
|
336 >>> print c.parser.parseString('command with args and terminator; and suffix').dump()
|
|
337 ['command', 'with args and terminator', ';', 'and suffix']
|
|
338 - args: with args and terminator
|
|
339 - command: command
|
|
340 - statement: ['command', 'with args and terminator', ';']
|
|
341 - args: with args and terminator
|
|
342 - command: command
|
|
343 - terminator: ;
|
|
344 - suffix: and suffix
|
|
345 - terminator: ;
|
|
346 >>> print c.parser.parseString('simple | piped').dump()
|
|
347 ['simple', '', '|', ' piped']
|
|
348 - command: simple
|
|
349 - pipeTo: piped
|
|
350 - statement: ['simple', '']
|
|
351 - command: simple
|
|
352 >>> print c.parser.parseString('double-pipe || is not a pipe').dump()
|
|
353 ['double', '-pipe || is not a pipe']
|
|
354 - args: -pipe || is not a pipe
|
|
355 - command: double
|
|
356 - statement: ['double', '-pipe || is not a pipe']
|
|
357 - args: -pipe || is not a pipe
|
|
358 - command: double
|
|
359 >>> print c.parser.parseString('command with args, terminator;sufx | piped').dump()
|
|
360 ['command', 'with args, terminator', ';', 'sufx', '|', ' piped']
|
|
361 - args: with args, terminator
|
|
362 - command: command
|
|
363 - pipeTo: piped
|
|
364 - statement: ['command', 'with args, terminator', ';']
|
|
365 - args: with args, terminator
|
|
366 - command: command
|
|
367 - terminator: ;
|
|
368 - suffix: sufx
|
|
369 - terminator: ;
|
|
370 >>> print c.parser.parseString('output into > afile.txt').dump()
|
|
371 ['output', 'into', '>', 'afile.txt']
|
|
372 - args: into
|
|
373 - command: output
|
|
374 - output: >
|
|
375 - outputTo: afile.txt
|
|
376 - statement: ['output', 'into']
|
|
377 - args: into
|
|
378 - command: output
|
|
379 >>> print c.parser.parseString('output into;sufx | pipethrume plz > afile.txt').dump()
|
|
380 ['output', 'into', ';', 'sufx', '|', ' pipethrume plz', '>', 'afile.txt']
|
|
381 - args: into
|
|
382 - command: output
|
|
383 - output: >
|
|
384 - outputTo: afile.txt
|
|
385 - pipeTo: pipethrume plz
|
|
386 - statement: ['output', 'into', ';']
|
|
387 - args: into
|
|
388 - command: output
|
|
389 - terminator: ;
|
|
390 - suffix: sufx
|
|
391 - terminator: ;
|
|
392 >>> print c.parser.parseString('output to paste buffer >> ').dump()
|
|
393 ['output', 'to paste buffer', '>>', '']
|
|
394 - args: to paste buffer
|
|
395 - command: output
|
|
396 - output: >>
|
|
397 - statement: ['output', 'to paste buffer']
|
|
398 - args: to paste buffer
|
|
399 - command: output
|
|
400 >>> print c.parser.parseString('ignore the /* commented | > */ stuff;').dump()
|
|
401 ['ignore', 'the /* commented | > */ stuff', ';', '']
|
|
402 - args: the /* commented | > */ stuff
|
|
403 - command: ignore
|
|
404 - statement: ['ignore', 'the /* commented | > */ stuff', ';']
|
|
405 - args: the /* commented | > */ stuff
|
|
406 - command: ignore
|
|
407 - terminator: ;
|
|
408 - terminator: ;
|
|
409 >>> print c.parser.parseString('has > inside;').dump()
|
|
410 ['has', '> inside', ';', '']
|
|
411 - args: > inside
|
|
412 - command: has
|
|
413 - statement: ['has', '> inside', ';']
|
|
414 - args: > inside
|
|
415 - command: has
|
|
416 - terminator: ;
|
|
417 - terminator: ;
|
|
418 >>> print c.parser.parseString('multiline has > inside an unfinished command').dump()
|
|
419 ['multiline', ' has > inside an unfinished command']
|
|
420 - multilineCommand: multiline
|
|
421 >>> print c.parser.parseString('multiline has > inside;').dump()
|
|
422 ['multiline', 'has > inside', ';', '']
|
|
423 - args: has > inside
|
|
424 - multilineCommand: multiline
|
|
425 - statement: ['multiline', 'has > inside', ';']
|
|
426 - args: has > inside
|
|
427 - multilineCommand: multiline
|
|
428 - terminator: ;
|
|
429 - terminator: ;
|
|
430 >>> print c.parser.parseString('multiline command /* with comment in progress;').dump()
|
|
431 ['multiline', ' command /* with comment in progress;']
|
|
432 - multilineCommand: multiline
|
|
433 >>> print c.parser.parseString('multiline command /* with comment complete */ is done;').dump()
|
|
434 ['multiline', 'command /* with comment complete */ is done', ';', '']
|
|
435 - args: command /* with comment complete */ is done
|
|
436 - multilineCommand: multiline
|
|
437 - statement: ['multiline', 'command /* with comment complete */ is done', ';']
|
|
438 - args: command /* with comment complete */ is done
|
|
439 - multilineCommand: multiline
|
|
440 - terminator: ;
|
|
441 - terminator: ;
|
|
442 >>> print c.parser.parseString('multiline command ends\n\n').dump()
|
|
443 ['multiline', 'command ends', '\n', '\n']
|
|
444 - args: command ends
|
|
445 - multilineCommand: multiline
|
|
446 - statement: ['multiline', 'command ends', '\n', '\n']
|
|
447 - args: command ends
|
|
448 - multilineCommand: multiline
|
|
449 - terminator: ['\n', '\n']
|
|
450 - terminator: ['\n', '\n']
|
|
451 '''
|
|
452 outputParser = (pyparsing.Literal('>>') | (pyparsing.WordStart() + '>') | pyparsing.Regex('[^=]>'))('output')
|
|
453
|
|
454 terminatorParser = pyparsing.Or([(hasattr(t, 'parseString') and t) or pyparsing.Literal(t) for t in self.terminators])('terminator')
|
|
455 stringEnd = pyparsing.stringEnd ^ '\nEOF'
|
|
456 self.multilineCommand = pyparsing.Or([pyparsing.Keyword(c, caseless=self.case_insensitive) for c in self.multilineCommands])('multilineCommand')
|
|
457 oneLineCommand = (~self.multilineCommand + pyparsing.Word(self.legalChars))('command')
|
|
458 pipe = pyparsing.Keyword('|', identChars='|')
|
|
459 self.commentGrammars.ignore(pyparsing.quotedString).setParseAction(lambda x: '')
|
|
460 self.commentInProgress.ignore(pyparsing.quotedString).ignore(pyparsing.cStyleComment)
|
|
461 afterElements = \
|
|
462 pyparsing.Optional(pipe + pyparsing.SkipTo(outputParser ^ stringEnd)('pipeTo')) + \
|
|
463 pyparsing.Optional(outputParser + pyparsing.SkipTo(stringEnd).setParseAction(lambda x: x[0].strip())('outputTo'))
|
|
464 if self.case_insensitive:
|
|
465 self.multilineCommand.setParseAction(lambda x: x[0].lower())
|
|
466 oneLineCommand.setParseAction(lambda x: x[0].lower())
|
|
467 if self.blankLinesAllowed:
|
|
468 self.blankLineTerminationParser = pyparsing.NoMatch
|
|
469 else:
|
|
470 self.blankLineTerminator = (pyparsing.lineEnd + pyparsing.lineEnd)('terminator')
|
|
471 self.blankLineTerminator.setResultsName('terminator')
|
|
472 self.blankLineTerminationParser = ((self.multilineCommand ^ oneLineCommand) + pyparsing.SkipTo(self.blankLineTerminator).setParseAction(lambda x: x[0].strip())('args') + self.blankLineTerminator)('statement')
|
|
473 self.multilineParser = (((self.multilineCommand ^ oneLineCommand) + SkipToLast(terminatorParser).setParseAction(lambda x: x[0].strip())('args') + terminatorParser)('statement') +
|
|
474 pyparsing.SkipTo(outputParser ^ pipe ^ stringEnd).setParseAction(lambda x: x[0].strip())('suffix') + afterElements)
|
|
475 self.singleLineParser = ((oneLineCommand + pyparsing.SkipTo(terminatorParser ^ stringEnd ^ pipe ^ outputParser).setParseAction(lambda x:x[0].strip())('args'))('statement') +
|
|
476 pyparsing.Optional(terminatorParser) + afterElements)
|
|
477 #self.multilineParser = self.multilineParser.setResultsName('multilineParser')
|
|
478 #self.singleLineParser = self.singleLineParser.setResultsName('singleLineParser')
|
|
479 #self.blankLineTerminationParser = self.blankLineTerminationParser.setResultsName('blankLineTerminatorParser')
|
|
480 self.parser = (
|
|
481 stringEnd |
|
|
482 self.prefixParser + self.multilineParser |
|
|
483 self.prefixParser + self.singleLineParser |
|
|
484 self.prefixParser + self.blankLineTerminationParser |
|
|
485 self.prefixParser + self.multilineCommand + pyparsing.SkipTo(stringEnd)
|
|
486 )
|
|
487 self.parser.ignore(pyparsing.quotedString).ignore(self.commentGrammars).ignore(self.commentInProgress)
|
|
488
|
|
489 inputMark = pyparsing.Literal('<')
|
|
490 inputMark.setParseAction(lambda x: '')
|
|
491 fileName = pyparsing.Word(self.legalChars + '/\\')
|
|
492 inputFrom = fileName('inputFrom')
|
|
493 inputFrom.setParseAction(replace_with_file_contents)
|
|
494 # a not-entirely-satisfactory way of distinguishing < as in "import from" from <
|
|
495 # as in "lesser than"
|
|
496 self.inputParser = inputMark + pyparsing.Optional(inputFrom) + pyparsing.Optional('>') + \
|
|
497 pyparsing.Optional(fileName) + (pyparsing.stringEnd | '|')
|
|
498 self.inputParser.ignore(pyparsing.quotedString).ignore(self.commentGrammars).ignore(self.commentInProgress)
|
|
499
|
|
500 def preparse(self, raw, **kwargs):
|
|
501 return raw
|
|
502
|
|
503 def parsed(self, raw, **kwargs):
|
|
504 if isinstance(raw, ParsedString):
|
|
505 p = raw
|
|
506 else:
|
|
507 raw = self.preparse(raw, **kwargs)
|
|
508 s = self.inputParser.transformString(raw.lstrip())
|
|
509 for (shortcut, expansion) in self.shortcuts.items():
|
|
510 if s.lower().startswith(shortcut):
|
|
511 s = s.replace(shortcut, expansion + ' ', 1)
|
|
512 break
|
|
513 result = self.parser.parseString(s)
|
|
514 result['command'] = result.multilineCommand or result.command
|
|
515 result['raw'] = raw
|
|
516 result['clean'] = self.commentGrammars.transformString(result.args)
|
|
517 result['expanded'] = s
|
|
518 p = ParsedString(result.clean)
|
|
519 p.parsed = result
|
|
520 p.parser = self.parsed
|
|
521 for (key, val) in kwargs.items():
|
|
522 p.parsed[key] = val
|
|
523 return p
|
|
524
|
|
525 def postparsing_precmd(self, statement):
|
|
526 stop = 0
|
|
527 return stop, statement
|
|
528 def postparsing_postcmd(self, stop):
|
|
529 return stop
|
|
530 def onecmd(self, line):
|
|
531 """Interpret the argument as though it had been typed in response
|
|
532 to the prompt.
|
|
533
|
|
534 This may be overridden, but should not normally need to be;
|
|
535 see the precmd() and postcmd() methods for useful execution hooks.
|
|
536 The return value is a flag indicating whether interpretation of
|
|
537 commands by the interpreter should stop.
|
|
538
|
|
539 This (`cmd2`) version of `onecmd` already override's `cmd`'s `onecmd`.
|
|
540
|
|
541 """
|
|
542 if not line:
|
|
543 return self.emptyline()
|
|
544 if not pyparsing.Or(self.commentGrammars).setParseAction(lambda x: '').transformString(line):
|
|
545 return 0 # command was empty except for comments
|
|
546 try:
|
|
547 statement = self.parsed(line)
|
|
548 while statement.parsed.multilineCommand and (statement.parsed.terminator == ''):
|
|
549 statement = '%s\n%s' % (statement.parsed.raw,
|
|
550 self.pseudo_raw_input(self.continuation_prompt))
|
|
551 statement = self.parsed(statement)
|
|
552 except Exception, e:
|
|
553 print e
|
|
554 return 0
|
|
555
|
|
556 try:
|
|
557 (stop, statement) = self.postparsing_precmd(statement)
|
|
558 except Exception, e:
|
|
559 print str(e)
|
|
560 return 0
|
|
561 if stop:
|
|
562 return self.postparsing_postcmd(stop)
|
|
563
|
|
564 if not statement.parsed.command:
|
|
565 return self.postparsing_postcmd(stop=0)
|
|
566
|
|
567 statekeeper = None
|
|
568
|
|
569 if statement.parsed.pipeTo:
|
|
570 redirect = subprocess.Popen(statement.parsed.pipeTo, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE)
|
|
571 statekeeper = Statekeeper(self, ('stdout',))
|
|
572 self.stdout = redirect.stdin
|
|
573 elif statement.parsed.output:
|
|
574 statekeeper = Statekeeper(self, ('stdout',))
|
|
575 if statement.parsed.outputTo:
|
|
576 mode = 'w'
|
|
577 if statement.parsed.output == '>>':
|
|
578 mode = 'a'
|
|
579 try:
|
|
580 self.stdout = open(os.path.expanduser(statement.parsed.outputTo), mode)
|
|
581 except OSError, e:
|
|
582 print e
|
|
583 return self.postparsing_postcmd(stop=0)
|
|
584 else:
|
|
585 statekeeper = Statekeeper(self, ('stdout',))
|
|
586 self.stdout = tempfile.TemporaryFile()
|
|
587 if statement.parsed.output == '>>':
|
|
588 self.stdout.write(getPasteBuffer())
|
|
589 try:
|
|
590 # "heart" of the command, replace's cmd's onecmd()
|
|
591 self.lastcmd = statement.parsed.expanded
|
|
592 try:
|
|
593 func = getattr(self, 'do_' + statement.parsed.command)
|
|
594 except AttributeError:
|
|
595 func = None
|
|
596 if self.abbrev: # accept shortened versions of commands
|
|
597 funcs = [func for (fname, func) in inspect.getmembers(
|
|
598 self, inspect.ismethod)
|
|
599 if fname.startswith('do_' + statement.parsed.command)]
|
|
600 if len(funcs) == 1:
|
|
601 func = funcs[0]
|
|
602 if not func:
|
|
603 return self.postparsing_postcmd(self.default(statement))
|
|
604 timestart = datetime.datetime.now()
|
|
605 stop = func(statement)
|
|
606 if self.timing:
|
|
607 print 'Elapsed: %s' % str(datetime.datetime.now() - timestart)
|
|
608 except Exception, e:
|
|
609 print e
|
|
610 try:
|
|
611 if statement.parsed.command not in self.excludeFromHistory:
|
|
612 self.history.append(statement.parsed.raw)
|
|
613 finally:
|
|
614 if statekeeper:
|
|
615 if statement.parsed.output and not statement.parsed.outputTo:
|
|
616 self.stdout.seek(0)
|
|
617 try:
|
|
618 writeToPasteBuffer(self.stdout.read())
|
|
619 except Exception, e:
|
|
620 print str(e)
|
|
621 elif statement.parsed.pipeTo:
|
|
622 for result in redirect.communicate():
|
|
623 statekeeper.stdout.write(result or '')
|
|
624 self.stdout.close()
|
|
625 statekeeper.restore()
|
|
626
|
|
627 return self.postparsing_postcmd(stop)
|
|
628
|
|
629 def pseudo_raw_input(self, prompt):
|
|
630 """copied from cmd's cmdloop; like raw_input, but accounts for changed stdin, stdout"""
|
|
631
|
|
632 if self.use_rawinput:
|
|
633 try:
|
|
634 line = raw_input(prompt)
|
|
635 except EOFError:
|
|
636 line = 'EOF'
|
|
637 else:
|
|
638 self.stdout.write(prompt)
|
|
639 self.stdout.flush()
|
|
640 line = self.stdin.readline()
|
|
641 if not len(line):
|
|
642 line = 'EOF'
|
|
643 else:
|
|
644 if line[-1] == '\n': # this was always true in Cmd
|
|
645 line = line[:-1]
|
|
646 return line
|
|
647
|
|
648 def cmdloop(self, intro=None):
|
|
649 """Repeatedly issue a prompt, accept input, parse an initial prefix
|
|
650 off the received input, and dispatch to action methods, passing them
|
|
651 the remainder of the line as argument.
|
|
652 """
|
|
653
|
|
654 # An almost perfect copy from Cmd; however, the pseudo_raw_input portion
|
|
655 # has been split out so that it can be called separately
|
|
656
|
|
657 self.preloop()
|
|
658 if self.use_rawinput and self.completekey:
|
|
659 try:
|
|
660 import readline
|
|
661 self.old_completer = readline.get_completer()
|
|
662 readline.set_completer(self.complete)
|
|
663 readline.parse_and_bind(self.completekey+": complete")
|
|
664 except ImportError:
|
|
665 pass
|
|
666 try:
|
|
667 if intro is not None:
|
|
668 self.intro = intro
|
|
669 if self.intro:
|
|
670 self.stdout.write(str(self.intro)+"\n")
|
|
671 stop = None
|
|
672 while not stop:
|
|
673 if self.cmdqueue:
|
|
674 line = self.cmdqueue.pop(0)
|
|
675 else:
|
|
676 line = self.pseudo_raw_input(self.prompt)
|
|
677 if (self.echo) and (isinstance(self.stdin, file)):
|
|
678 self.stdout.write(line + '\n')
|
|
679 line = self.precmd(line)
|
|
680 stop = self.onecmd(line)
|
|
681 stop = self.postcmd(stop, line)
|
|
682 self.postloop()
|
|
683 finally:
|
|
684 if self.use_rawinput and self.completekey:
|
|
685 try:
|
|
686 import readline
|
|
687 readline.set_completer(self.old_completer)
|
|
688 except ImportError:
|
|
689 pass
|
|
690 return stop
|
|
691
|
|
692 def do_EOF(self, arg):
|
|
693 return True
|
|
694 do_eof = do_EOF
|
|
695
|
|
696 def showParam(self, param):
|
|
697 any_shown = False
|
|
698 param = param.strip().lower()
|
|
699 for p in self.settable:
|
|
700 if p.startswith(param):
|
|
701 val = getattr(self, p)
|
|
702 self.stdout.write('%s: %s\n' % (p, str(getattr(self, p))))
|
|
703 any_shown = True
|
|
704 if not any_shown:
|
|
705 print "Parameter '%s' not supported (type 'show' for list of parameters)." % param
|
|
706
|
|
707 def do_quit(self, arg):
|
|
708 return self._STOP_AND_EXIT
|
|
709 do_exit = do_quit
|
|
710 do_q = do_quit
|
|
711
|
|
712 def do_show(self, arg):
|
|
713 '''Shows value of a parameter.'''
|
|
714 if arg.strip():
|
|
715 self.showParam(arg)
|
|
716 else:
|
|
717 for param in self.settable:
|
|
718 self.showParam(param)
|
|
719
|
|
720 def do_set(self, arg):
|
|
721 '''Sets a cmd2 parameter. Accepts abbreviated parameter names so long as there is no ambiguity.
|
|
722 Call without arguments for a list of settable parameters with their values.'''
|
|
723 try:
|
|
724 paramName, val = arg.split(None, 1)
|
|
725 paramName = paramName.strip().lower()
|
|
726 hits = [paramName in p for p in self.settable]
|
|
727 if hits.count(True) == 1:
|
|
728 paramName = self.settable[hits.index(True)]
|
|
729 currentVal = getattr(self, paramName)
|
|
730 if (val[0] == val[-1]) and val[0] in ("'", '"'):
|
|
731 val = val[1:-1]
|
|
732 else:
|
|
733 val = cast(currentVal, val)
|
|
734 setattr(self, paramName, val)
|
|
735 self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val))
|
|
736 if currentVal != val:
|
|
737 try:
|
|
738 onchange_hook = getattr(self, '_onchange_%s' % paramName)
|
|
739 onchange_hook(old=currentVal, new=val)
|
|
740 except AttributeError:
|
|
741 pass
|
|
742 else:
|
|
743 self.do_show(paramName)
|
|
744 except (ValueError, AttributeError, NotSettableError), e:
|
|
745 self.do_show(arg)
|
|
746
|
|
747 def do_pause(self, arg):
|
|
748 'Displays the specified text then waits for the user to press RETURN.'
|
|
749 raw_input(arg + '\n')
|
|
750
|
|
751 def do_shell(self, arg):
|
|
752 'execute a command as if at the OS prompt.'
|
|
753 os.system(arg)
|
|
754
|
|
755 def do_py(self, arg):
|
|
756 '''
|
|
757 py <command>: Executes a Python command.
|
|
758 py: Enters interactive Python mode (end with `end py`).
|
|
759 '''
|
|
760 if arg.strip():
|
|
761 try:
|
|
762 result = eval(arg, self.pystate)
|
|
763 print repr(result)
|
|
764 except SyntaxError:
|
|
765 try:
|
|
766 exec(arg, self.pystate)
|
|
767 except Exception:
|
|
768 raise
|
|
769 except Exception, e:
|
|
770 print e
|
|
771 else:
|
|
772 print 'Now accepting python commands; end with `end py`'
|
|
773 buffer = [self.pseudo_raw_input('>>> ')]
|
|
774 while buffer[-1].lower().split()[:2] != ['end','py']:
|
|
775 try:
|
|
776 buf = '\n'.join(buffer)
|
|
777 try:
|
|
778 result = eval(buf, self.pystate)
|
|
779 print repr(result)
|
|
780 except SyntaxError:
|
|
781 exec(buf, self.pystate)
|
|
782 buffer = [self.pseudo_raw_input('>>> ')]
|
|
783 except SyntaxError:
|
|
784 buffer.append(self.pseudo_raw_input('... '))
|
|
785 except Exception, e:
|
|
786 print e
|
|
787 buffer = [self.pseudo_raw_input('>>> ')]
|
|
788
|
|
789 def do_history(self, arg):
|
|
790 """history [arg]: lists past commands issued
|
|
791
|
|
792 no arg -> list all
|
|
793 arg is integer -> list one history item, by index
|
|
794 arg is string -> string search
|
|
795 arg is /enclosed in forward-slashes/ -> regular expression search
|
|
796 """
|
|
797 if arg:
|
|
798 history = self.history.get(arg)
|
|
799 else:
|
|
800 history = self.history
|
|
801 for hi in history:
|
|
802 self.stdout.write(hi.pr())
|
|
803 def last_matching(self, arg):
|
|
804 try:
|
|
805 if arg:
|
|
806 return self.history.get(arg)[-1]
|
|
807 else:
|
|
808 return self.history[-1]
|
|
809 except IndexError:
|
|
810 return None
|
|
811 def do_list(self, arg):
|
|
812 """list [arg]: lists last command issued
|
|
813
|
|
814 no arg -> list absolute last
|
|
815 arg is integer -> list one history item, by index
|
|
816 - arg, arg - (integer) -> list up to or after #arg
|
|
817 arg is string -> list last command matching string search
|
|
818 arg is /enclosed in forward-slashes/ -> regular expression search
|
|
819 """
|
|
820 try:
|
|
821 self.stdout.write(self.last_matching(arg).pr())
|
|
822 except:
|
|
823 pass
|
|
824 do_hi = do_history
|
|
825 do_l = do_list
|
|
826 do_li = do_list
|
|
827
|
|
828 def do_ed(self, arg):
|
|
829 """ed: edit most recent command in text editor
|
|
830 ed [N]: edit numbered command from history
|
|
831 ed [filename]: edit specified file name
|
|
832
|
|
833 commands are run after editor is closed.
|
|
834 "set edit (program-name)" or set EDITOR environment variable
|
|
835 to control which editing program is used."""
|
|
836 if not self.editor:
|
|
837 print "please use 'set editor' to specify your text editing program of choice."
|
|
838 return
|
|
839 filename = self.default_file_name
|
|
840 if arg:
|
|
841 try:
|
|
842 buffer = self.last_matching(int(arg))
|
|
843 except ValueError:
|
|
844 filename = arg
|
|
845 buffer = ''
|
|
846 else:
|
|
847 buffer = self.history[-1]
|
|
848
|
|
849 if buffer:
|
|
850 f = open(os.path.expanduser(filename), 'w')
|
|
851 f.write(buffer or '')
|
|
852 f.close()
|
|
853
|
|
854 os.system('%s %s' % (self.editor, filename))
|
|
855 self.do__load(filename)
|
|
856 do_edit = do_ed
|
|
857
|
|
858 saveparser = (pyparsing.Optional(pyparsing.Word(pyparsing.nums)^'*')("idx") +
|
|
859 pyparsing.Optional(pyparsing.Word(legalChars + '/\\'))("fname") +
|
|
860 pyparsing.stringEnd)
|
|
861 def do_save(self, arg):
|
|
862 """`save [N] [filename.ext]`
|
|
863 Saves command from history to file.
|
|
864 N => Number of command (from history), or `*`;
|
|
865 most recent command if omitted"""
|
|
866
|
|
867 try:
|
|
868 args = self.saveparser.parseString(arg)
|
|
869 except pyparsing.ParseException:
|
|
870 print self.do_save.__doc__
|
|
871 return
|
|
872 fname = args.fname or self.default_file_name
|
|
873 if args.idx == '*':
|
|
874 saveme = '\n\n'.join(self.history[:])
|
|
875 elif args.idx:
|
|
876 saveme = self.history[int(args.idx)-1]
|
|
877 else:
|
|
878 saveme = self.history[-1]
|
|
879 try:
|
|
880 f = open(os.path.expanduser(fname), 'w')
|
|
881 f.write(saveme)
|
|
882 f.close()
|
|
883 print 'Saved to %s' % (fname)
|
|
884 except Exception, e:
|
|
885 print 'Error saving %s: %s' % (fname, str(e))
|
|
886
|
|
887 urlre = re.compile('(https?://[-\\w\\./]+)')
|
|
888 def do_load(self, fname=None):
|
|
889 """Runs script of command(s) from a file or URL."""
|
|
890 if fname is None:
|
|
891 fname = self.default_file_name
|
|
892 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt','continuation_prompt'))
|
|
893 try:
|
|
894 if isinstance(fname, file):
|
|
895 target = open(fname, 'r')
|
|
896 else:
|
|
897 match = self.urlre.match(fname)
|
|
898 if match:
|
|
899 target = urllib.urlopen(match.group(1))
|
|
900 else:
|
|
901 fname = os.path.expanduser(fname)
|
|
902 try:
|
|
903 target = open(os.path.expanduser(fname), 'r')
|
|
904 except IOError, e:
|
|
905 target = open('%s.%s' % (os.path.expanduser(fname),
|
|
906 self.defaultExtension), 'r')
|
|
907 except IOError, e:
|
|
908 print 'Problem accessing script from %s: \n%s' % (fname, e)
|
|
909 keepstate.restore()
|
|
910 return
|
|
911 self.stdin = target
|
|
912 self.use_rawinput = False
|
|
913 self.prompt = self.continuation_prompt = ''
|
|
914 stop = self.cmdloop()
|
|
915 self.stdin.close()
|
|
916 keepstate.restore()
|
|
917 self.lastcmd = ''
|
|
918 return (stop == self._STOP_AND_EXIT) and self._STOP_AND_EXIT
|
|
919 do__load = do_load # avoid an unfortunate legacy use of do_load from sqlpython
|
|
920
|
|
921 def do_run(self, arg):
|
|
922 """run [arg]: re-runs an earlier command
|
|
923
|
|
924 no arg -> run most recent command
|
|
925 arg is integer -> run one history item, by index
|
|
926 arg is string -> run most recent command by string search
|
|
927 arg is /enclosed in forward-slashes/ -> run most recent by regex
|
|
928 """
|
|
929 'run [N]: runs the SQL that was run N commands ago'
|
|
930 runme = self.last_matching(arg)
|
|
931 print runme
|
|
932 if runme:
|
|
933 runme = self.precmd(runme)
|
|
934 stop = self.onecmd(runme)
|
|
935 stop = self.postcmd(stop, runme)
|
|
936 do_r = do_run
|
|
937
|
|
938 def fileimport(self, statement, source):
|
|
939 try:
|
|
940 f = open(os.path.expanduser(source))
|
|
941 except IOError:
|
|
942 self.stdout.write("Couldn't read from file %s\n" % source)
|
|
943 return ''
|
|
944 data = f.read()
|
|
945 f.close()
|
|
946 return data
|
|
947
|
|
948 class HistoryItem(str):
|
|
949 def __init__(self, instr):
|
|
950 str.__init__(self)
|
|
951 self.lowercase = self.lower()
|
|
952 self.idx = None
|
|
953 def pr(self):
|
|
954 return '-------------------------[%d]\n%s\n' % (self.idx, str(self))
|
|
955
|
|
956 class History(list):
|
|
957 rangeFrom = re.compile(r'^([\d])+\s*\-$')
|
|
958 def append(self, new):
|
|
959 new = HistoryItem(new)
|
|
960 list.append(self, new)
|
|
961 new.idx = len(self)
|
|
962 def extend(self, new):
|
|
963 for n in new:
|
|
964 self.append(n)
|
|
965 def get(self, getme):
|
|
966 try:
|
|
967 getme = int(getme)
|
|
968 if getme < 0:
|
|
969 return self[:(-1 * getme)]
|
|
970 else:
|
|
971 return [self[getme-1]]
|
|
972 except IndexError:
|
|
973 return []
|
|
974 except (ValueError, TypeError):
|
|
975 getme = getme.strip()
|
|
976 mtch = self.rangeFrom.search(getme)
|
|
977 if mtch:
|
|
978 return self[(int(mtch.group(1))-1):]
|
|
979 if getme.startswith(r'/') and getme.endswith(r'/'):
|
|
980 finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE)
|
|
981 def isin(hi):
|
|
982 return finder.search(hi)
|
|
983 else:
|
|
984 def isin(hi):
|
|
985 return (getme.lower() in hi.lowercase)
|
|
986 return [itm for itm in self if isin(itm)]
|
|
987
|
|
988 class NotSettableError(Exception):
|
|
989 pass
|
|
990
|
|
991 def cast(current, new):
|
|
992 """Tries to force a new value into the same type as the current."""
|
|
993 typ = type(current)
|
|
994 if typ == bool:
|
|
995 try:
|
|
996 return bool(int(new))
|
|
997 except ValueError, TypeError:
|
|
998 pass
|
|
999 try:
|
|
1000 new = new.lower()
|
|
1001 except:
|
|
1002 pass
|
|
1003 if (new=='on') or (new[0] in ('y','t')):
|
|
1004 return True
|
|
1005 if (new=='off') or (new[0] in ('n','f')):
|
|
1006 return False
|
|
1007 else:
|
|
1008 try:
|
|
1009 return typ(new)
|
|
1010 except:
|
|
1011 pass
|
|
1012 print "Problem setting parameter (now %s) to %s; incorrect type?" % (current, new)
|
|
1013 return current
|
|
1014
|
|
1015 class Statekeeper(object):
|
|
1016 def __init__(self, obj, attribs):
|
|
1017 self.obj = obj
|
|
1018 self.attribs = attribs
|
|
1019 self.save()
|
|
1020 def save(self):
|
|
1021 for attrib in self.attribs:
|
|
1022 setattr(self, attrib, getattr(self.obj, attrib))
|
|
1023 def restore(self):
|
|
1024 for attrib in self.attribs:
|
|
1025 setattr(self.obj, attrib, getattr(self, attrib))
|
|
1026
|
|
1027 class Borg(object):
|
|
1028 '''All instances of any Borg subclass will share state.
|
|
1029 from Python Cookbook, 2nd Ed., recipe 6.16'''
|
|
1030 _shared_state = {}
|
|
1031 def __new__(cls, *a, **k):
|
|
1032 obj = object.__new__(cls, *a, **k)
|
|
1033 obj.__dict__ = cls._shared_state
|
|
1034 return obj
|
|
1035
|
|
1036 class OutputTrap(Borg):
|
|
1037 '''Instantiate an OutputTrap to divert/capture ALL stdout output. For use in unit testing.
|
|
1038 Call `tearDown()` to return to normal output.'''
|
|
1039 def __init__(self):
|
|
1040 self.old_stdout = sys.stdout
|
|
1041 self.trap = tempfile.TemporaryFile()
|
|
1042 sys.stdout = self.trap
|
|
1043 def read(self):
|
|
1044 self.trap.seek(0)
|
|
1045 result = self.trap.read()
|
|
1046 self.trap.truncate(0)
|
|
1047 return result.strip('\x00')
|
|
1048 def tearDown(self):
|
|
1049 sys.stdout = self.old_stdout
|
|
1050
|
|
1051 class Cmd2TestCase(unittest.TestCase):
|
|
1052 '''Subclass this, setting CmdApp and transcriptFileName, to make a unittest.TestCase class
|
|
1053 that will execute the commands in transcriptFileName and expect the results shown.
|
|
1054 See example.py'''
|
|
1055 CmdApp = None
|
|
1056 transcriptFileName = ''
|
|
1057 def setUp(self):
|
|
1058 if self.CmdApp:
|
|
1059 self.outputTrap = OutputTrap()
|
|
1060 self.cmdapp = self.CmdApp()
|
|
1061 try:
|
|
1062 tfile = open(os.path.expanduser(self.transcriptFileName))
|
|
1063 self.transcript = iter(tfile.readlines())
|
|
1064 tfile.close()
|
|
1065 except IOError:
|
|
1066 self.transcript = []
|
|
1067 def assertEqualEnough(self, got, expected, message):
|
|
1068 got = got.strip().splitlines()
|
|
1069 expected = expected.strip().splitlines()
|
|
1070 self.assertEqual(len(got), len(expected), message)
|
|
1071 for (linegot, lineexpected) in zip(got, expected):
|
|
1072 matchme = re.escape(lineexpected.strip()).replace('\\*', '.*'). \
|
|
1073 replace('\\ ', ' ')
|
|
1074 self.assert_(re.match(matchme, linegot.strip()), message)
|
|
1075 def testall(self):
|
|
1076 if self.CmdApp:
|
|
1077 lineNum = 0
|
|
1078 try:
|
|
1079 line = self.transcript.next()
|
|
1080 while True:
|
|
1081 while not line.startswith(self.cmdapp.prompt):
|
|
1082 line = self.transcript.next()
|
|
1083 command = [line[len(self.cmdapp.prompt):]]
|
|
1084 line = self.transcript.next()
|
|
1085 while line.startswith(self.cmdapp.continuation_prompt):
|
|
1086 command.append(line[len(self.cmdapp.continuation_prompt):])
|
|
1087 line = self.transcript.next()
|
|
1088 command = ''.join(command)
|
|
1089 self.cmdapp.onecmd(command)
|
|
1090 result = self.outputTrap.read()
|
|
1091 if line.startswith(self.cmdapp.prompt):
|
|
1092 self.assertEqualEnough(result.strip(), '',
|
|
1093 '\nFile %s, line %d\nCommand was:\n%s\nExpected: (nothing) \nGot:\n%s\n' %
|
|
1094 (self.transcriptFileName, lineNum, command, result))
|
|
1095 continue
|
|
1096 expected = []
|
|
1097 while not line.startswith(self.cmdapp.prompt):
|
|
1098 expected.append(line)
|
|
1099 line = self.transcript.next()
|
|
1100 expected = ''.join(expected)
|
|
1101 self.assertEqualEnough(expected.strip(), result.strip(),
|
|
1102 '\nFile %s, line %d\nCommand was:\n%s\nExpected:\n%s\nGot:\n%s\n' %
|
|
1103 (self.transcriptFileName, lineNum, command, expected, result))
|
|
1104 # this needs to account for a line-by-line strip()ping
|
|
1105 except StopIteration:
|
|
1106 pass
|
|
1107 # catch the final output?
|
|
1108 def tearDown(self):
|
|
1109 if self.CmdApp:
|
|
1110 self.outputTrap.tearDown()
|
|
1111
|
|
1112 if __name__ == '__main__':
|
|
1113 doctest.testmod(optionflags = doctest.NORMALIZE_WHITESPACE)
|
|
1114 #c = Cmd()
|