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