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
|
231
|
755 def _attempt_py_command(self, arg):
|
|
756 try:
|
|
757 result = eval(arg, self.pystate)
|
|
758 print repr(result)
|
|
759 except SyntaxError:
|
|
760 exec(arg, self.pystate)
|
|
761 return
|
|
762
|
|
763 def do_py(self, arg, escape = 'cmd'):
|
230
|
764 '''
|
|
765 py <command>: Executes a Python command.
|
|
766 py: Enters interactive Python mode (end with `end py`).
|
|
767 '''
|
|
768 if arg.strip():
|
231
|
769 self._attempt_py_command(arg)
|
230
|
770 else:
|
|
771 print 'Now accepting python commands; end with `end py`'
|
|
772 buffer = [self.pseudo_raw_input('>>> ')]
|
|
773 while buffer[-1].lower().split()[:2] != ['end','py']:
|
231
|
774 if buffer[-1].lower().split()[:1] == [escape]:
|
|
775 self.onecmd(' '.join(buffer[-1].split()[1:]))
|
|
776 buffer = [self.pseudo_raw_input('>>> ')]
|
|
777 continue
|
|
778 else:
|
230
|
779 try:
|
231
|
780 self._attempt_py_command('\n'.join(buffer))
|
|
781 buffer = [self.pseudo_raw_input('>>> ')]
|
230
|
782 except SyntaxError:
|
231
|
783 buffer.append(self.pseudo_raw_input('... '))
|
|
784 except Exception, e:
|
|
785 print e
|
|
786 buffer = [self.pseudo_raw_input('>>> ')]
|
230
|
787
|
|
788 def do_history(self, arg):
|
|
789 """history [arg]: lists past commands issued
|
|
790
|
|
791 no arg -> list all
|
|
792 arg is integer -> list one history item, by index
|
|
793 arg is string -> string search
|
|
794 arg is /enclosed in forward-slashes/ -> regular expression search
|
|
795 """
|
|
796 if arg:
|
|
797 history = self.history.get(arg)
|
|
798 else:
|
|
799 history = self.history
|
|
800 for hi in history:
|
|
801 self.stdout.write(hi.pr())
|
|
802 def last_matching(self, arg):
|
|
803 try:
|
|
804 if arg:
|
|
805 return self.history.get(arg)[-1]
|
|
806 else:
|
|
807 return self.history[-1]
|
|
808 except IndexError:
|
|
809 return None
|
|
810 def do_list(self, arg):
|
|
811 """list [arg]: lists last command issued
|
|
812
|
|
813 no arg -> list absolute last
|
|
814 arg is integer -> list one history item, by index
|
|
815 - arg, arg - (integer) -> list up to or after #arg
|
|
816 arg is string -> list last command matching string search
|
|
817 arg is /enclosed in forward-slashes/ -> regular expression search
|
|
818 """
|
|
819 try:
|
|
820 self.stdout.write(self.last_matching(arg).pr())
|
|
821 except:
|
|
822 pass
|
|
823 do_hi = do_history
|
|
824 do_l = do_list
|
|
825 do_li = do_list
|
|
826
|
|
827 def do_ed(self, arg):
|
|
828 """ed: edit most recent command in text editor
|
|
829 ed [N]: edit numbered command from history
|
|
830 ed [filename]: edit specified file name
|
|
831
|
|
832 commands are run after editor is closed.
|
|
833 "set edit (program-name)" or set EDITOR environment variable
|
|
834 to control which editing program is used."""
|
|
835 if not self.editor:
|
|
836 print "please use 'set editor' to specify your text editing program of choice."
|
|
837 return
|
|
838 filename = self.default_file_name
|
|
839 if arg:
|
|
840 try:
|
|
841 buffer = self.last_matching(int(arg))
|
|
842 except ValueError:
|
|
843 filename = arg
|
|
844 buffer = ''
|
|
845 else:
|
|
846 buffer = self.history[-1]
|
|
847
|
|
848 if buffer:
|
|
849 f = open(os.path.expanduser(filename), 'w')
|
|
850 f.write(buffer or '')
|
|
851 f.close()
|
|
852
|
|
853 os.system('%s %s' % (self.editor, filename))
|
|
854 self.do__load(filename)
|
|
855 do_edit = do_ed
|
|
856
|
|
857 saveparser = (pyparsing.Optional(pyparsing.Word(pyparsing.nums)^'*')("idx") +
|
|
858 pyparsing.Optional(pyparsing.Word(legalChars + '/\\'))("fname") +
|
|
859 pyparsing.stringEnd)
|
|
860 def do_save(self, arg):
|
|
861 """`save [N] [filename.ext]`
|
|
862 Saves command from history to file.
|
|
863 N => Number of command (from history), or `*`;
|
|
864 most recent command if omitted"""
|
|
865
|
|
866 try:
|
|
867 args = self.saveparser.parseString(arg)
|
|
868 except pyparsing.ParseException:
|
|
869 print self.do_save.__doc__
|
|
870 return
|
|
871 fname = args.fname or self.default_file_name
|
|
872 if args.idx == '*':
|
|
873 saveme = '\n\n'.join(self.history[:])
|
|
874 elif args.idx:
|
|
875 saveme = self.history[int(args.idx)-1]
|
|
876 else:
|
|
877 saveme = self.history[-1]
|
|
878 try:
|
|
879 f = open(os.path.expanduser(fname), 'w')
|
|
880 f.write(saveme)
|
|
881 f.close()
|
|
882 print 'Saved to %s' % (fname)
|
|
883 except Exception, e:
|
|
884 print 'Error saving %s: %s' % (fname, str(e))
|
|
885
|
|
886 urlre = re.compile('(https?://[-\\w\\./]+)')
|
|
887 def do_load(self, fname=None):
|
|
888 """Runs script of command(s) from a file or URL."""
|
|
889 if fname is None:
|
|
890 fname = self.default_file_name
|
|
891 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt','continuation_prompt'))
|
|
892 try:
|
|
893 if isinstance(fname, file):
|
|
894 target = open(fname, 'r')
|
|
895 else:
|
|
896 match = self.urlre.match(fname)
|
|
897 if match:
|
|
898 target = urllib.urlopen(match.group(1))
|
|
899 else:
|
|
900 fname = os.path.expanduser(fname)
|
|
901 try:
|
|
902 target = open(os.path.expanduser(fname), 'r')
|
|
903 except IOError, e:
|
|
904 target = open('%s.%s' % (os.path.expanduser(fname),
|
|
905 self.defaultExtension), 'r')
|
|
906 except IOError, e:
|
|
907 print 'Problem accessing script from %s: \n%s' % (fname, e)
|
|
908 keepstate.restore()
|
|
909 return
|
|
910 self.stdin = target
|
|
911 self.use_rawinput = False
|
|
912 self.prompt = self.continuation_prompt = ''
|
|
913 stop = self.cmdloop()
|
|
914 self.stdin.close()
|
|
915 keepstate.restore()
|
|
916 self.lastcmd = ''
|
|
917 return (stop == self._STOP_AND_EXIT) and self._STOP_AND_EXIT
|
|
918 do__load = do_load # avoid an unfortunate legacy use of do_load from sqlpython
|
|
919
|
|
920 def do_run(self, arg):
|
|
921 """run [arg]: re-runs an earlier command
|
|
922
|
|
923 no arg -> run most recent command
|
|
924 arg is integer -> run one history item, by index
|
|
925 arg is string -> run most recent command by string search
|
|
926 arg is /enclosed in forward-slashes/ -> run most recent by regex
|
|
927 """
|
|
928 'run [N]: runs the SQL that was run N commands ago'
|
|
929 runme = self.last_matching(arg)
|
|
930 print runme
|
|
931 if runme:
|
|
932 runme = self.precmd(runme)
|
|
933 stop = self.onecmd(runme)
|
|
934 stop = self.postcmd(stop, runme)
|
|
935 do_r = do_run
|
|
936
|
|
937 def fileimport(self, statement, source):
|
|
938 try:
|
|
939 f = open(os.path.expanduser(source))
|
|
940 except IOError:
|
|
941 self.stdout.write("Couldn't read from file %s\n" % source)
|
|
942 return ''
|
|
943 data = f.read()
|
|
944 f.close()
|
|
945 return data
|
|
946
|
|
947 class HistoryItem(str):
|
|
948 def __init__(self, instr):
|
|
949 str.__init__(self)
|
|
950 self.lowercase = self.lower()
|
|
951 self.idx = None
|
|
952 def pr(self):
|
|
953 return '-------------------------[%d]\n%s\n' % (self.idx, str(self))
|
|
954
|
|
955 class History(list):
|
|
956 rangeFrom = re.compile(r'^([\d])+\s*\-$')
|
|
957 def append(self, new):
|
|
958 new = HistoryItem(new)
|
|
959 list.append(self, new)
|
|
960 new.idx = len(self)
|
|
961 def extend(self, new):
|
|
962 for n in new:
|
|
963 self.append(n)
|
|
964 def get(self, getme):
|
|
965 try:
|
|
966 getme = int(getme)
|
|
967 if getme < 0:
|
|
968 return self[:(-1 * getme)]
|
|
969 else:
|
|
970 return [self[getme-1]]
|
|
971 except IndexError:
|
|
972 return []
|
|
973 except (ValueError, TypeError):
|
|
974 getme = getme.strip()
|
|
975 mtch = self.rangeFrom.search(getme)
|
|
976 if mtch:
|
|
977 return self[(int(mtch.group(1))-1):]
|
|
978 if getme.startswith(r'/') and getme.endswith(r'/'):
|
|
979 finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE)
|
|
980 def isin(hi):
|
|
981 return finder.search(hi)
|
|
982 else:
|
|
983 def isin(hi):
|
|
984 return (getme.lower() in hi.lowercase)
|
|
985 return [itm for itm in self if isin(itm)]
|
|
986
|
|
987 class NotSettableError(Exception):
|
|
988 pass
|
|
989
|
|
990 def cast(current, new):
|
|
991 """Tries to force a new value into the same type as the current."""
|
|
992 typ = type(current)
|
|
993 if typ == bool:
|
|
994 try:
|
|
995 return bool(int(new))
|
|
996 except ValueError, TypeError:
|
|
997 pass
|
|
998 try:
|
|
999 new = new.lower()
|
|
1000 except:
|
|
1001 pass
|
|
1002 if (new=='on') or (new[0] in ('y','t')):
|
|
1003 return True
|
|
1004 if (new=='off') or (new[0] in ('n','f')):
|
|
1005 return False
|
|
1006 else:
|
|
1007 try:
|
|
1008 return typ(new)
|
|
1009 except:
|
|
1010 pass
|
|
1011 print "Problem setting parameter (now %s) to %s; incorrect type?" % (current, new)
|
|
1012 return current
|
|
1013
|
|
1014 class Statekeeper(object):
|
|
1015 def __init__(self, obj, attribs):
|
|
1016 self.obj = obj
|
|
1017 self.attribs = attribs
|
|
1018 self.save()
|
|
1019 def save(self):
|
|
1020 for attrib in self.attribs:
|
|
1021 setattr(self, attrib, getattr(self.obj, attrib))
|
|
1022 def restore(self):
|
|
1023 for attrib in self.attribs:
|
|
1024 setattr(self.obj, attrib, getattr(self, attrib))
|
|
1025
|
|
1026 class Borg(object):
|
|
1027 '''All instances of any Borg subclass will share state.
|
|
1028 from Python Cookbook, 2nd Ed., recipe 6.16'''
|
|
1029 _shared_state = {}
|
|
1030 def __new__(cls, *a, **k):
|
|
1031 obj = object.__new__(cls, *a, **k)
|
|
1032 obj.__dict__ = cls._shared_state
|
|
1033 return obj
|
|
1034
|
|
1035 class OutputTrap(Borg):
|
|
1036 '''Instantiate an OutputTrap to divert/capture ALL stdout output. For use in unit testing.
|
|
1037 Call `tearDown()` to return to normal output.'''
|
|
1038 def __init__(self):
|
|
1039 self.old_stdout = sys.stdout
|
|
1040 self.trap = tempfile.TemporaryFile()
|
|
1041 sys.stdout = self.trap
|
|
1042 def read(self):
|
|
1043 self.trap.seek(0)
|
|
1044 result = self.trap.read()
|
|
1045 self.trap.truncate(0)
|
|
1046 return result.strip('\x00')
|
|
1047 def tearDown(self):
|
|
1048 sys.stdout = self.old_stdout
|
|
1049
|
|
1050 class Cmd2TestCase(unittest.TestCase):
|
|
1051 '''Subclass this, setting CmdApp and transcriptFileName, to make a unittest.TestCase class
|
|
1052 that will execute the commands in transcriptFileName and expect the results shown.
|
|
1053 See example.py'''
|
|
1054 CmdApp = None
|
|
1055 transcriptFileName = ''
|
|
1056 def setUp(self):
|
|
1057 if self.CmdApp:
|
|
1058 self.outputTrap = OutputTrap()
|
|
1059 self.cmdapp = self.CmdApp()
|
|
1060 try:
|
|
1061 tfile = open(os.path.expanduser(self.transcriptFileName))
|
|
1062 self.transcript = iter(tfile.readlines())
|
|
1063 tfile.close()
|
|
1064 except IOError:
|
|
1065 self.transcript = []
|
|
1066 def assertEqualEnough(self, got, expected, message):
|
|
1067 got = got.strip().splitlines()
|
|
1068 expected = expected.strip().splitlines()
|
|
1069 self.assertEqual(len(got), len(expected), message)
|
|
1070 for (linegot, lineexpected) in zip(got, expected):
|
|
1071 matchme = re.escape(lineexpected.strip()).replace('\\*', '.*'). \
|
|
1072 replace('\\ ', ' ')
|
|
1073 self.assert_(re.match(matchme, linegot.strip()), message)
|
|
1074 def testall(self):
|
|
1075 if self.CmdApp:
|
|
1076 lineNum = 0
|
|
1077 try:
|
|
1078 line = self.transcript.next()
|
|
1079 while True:
|
|
1080 while not line.startswith(self.cmdapp.prompt):
|
|
1081 line = self.transcript.next()
|
|
1082 command = [line[len(self.cmdapp.prompt):]]
|
|
1083 line = self.transcript.next()
|
|
1084 while line.startswith(self.cmdapp.continuation_prompt):
|
|
1085 command.append(line[len(self.cmdapp.continuation_prompt):])
|
|
1086 line = self.transcript.next()
|
|
1087 command = ''.join(command)
|
|
1088 self.cmdapp.onecmd(command)
|
|
1089 result = self.outputTrap.read()
|
|
1090 if line.startswith(self.cmdapp.prompt):
|
|
1091 self.assertEqualEnough(result.strip(), '',
|
|
1092 '\nFile %s, line %d\nCommand was:\n%s\nExpected: (nothing) \nGot:\n%s\n' %
|
|
1093 (self.transcriptFileName, lineNum, command, result))
|
|
1094 continue
|
|
1095 expected = []
|
|
1096 while not line.startswith(self.cmdapp.prompt):
|
|
1097 expected.append(line)
|
|
1098 line = self.transcript.next()
|
|
1099 expected = ''.join(expected)
|
|
1100 self.assertEqualEnough(expected.strip(), result.strip(),
|
|
1101 '\nFile %s, line %d\nCommand was:\n%s\nExpected:\n%s\nGot:\n%s\n' %
|
|
1102 (self.transcriptFileName, lineNum, command, expected, result))
|
|
1103 # this needs to account for a line-by-line strip()ping
|
|
1104 except StopIteration:
|
|
1105 pass
|
|
1106 # catch the final output?
|
|
1107 def tearDown(self):
|
|
1108 if self.CmdApp:
|
|
1109 self.outputTrap.tearDown()
|
|
1110
|
|
1111 if __name__ == '__main__':
|
|
1112 doctest.testmod(optionflags = doctest.NORMALIZE_WHITESPACE)
|
|
1113 #c = Cmd()
|