Mercurial > python-cmd2
annotate cmd2.py @ 241:af17ead6449d
shortened docstring to avoid word wrap
author | catherine@dellzilla |
---|---|
date | Tue, 24 Mar 2009 15:25:28 -0400 |
parents | a31cf334bc16 |
children | d36ffc16f575 |
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 | |
237 | 286 Settable parameters: %(settable)s\n""" % \ |
230 | 287 { 'casesensitive': (self.case_insensitive and 'not ') or '', |
288 'terminators': str(self.terminators), | |
289 'settable': ' '.join(self.settable) | |
290 }) | |
291 | |
292 def do_help(self, arg): | |
293 try: | |
294 fn = getattr(self, 'do_' + arg) | |
295 if fn and fn.optionParser: | |
296 fn.optionParser.print_help(file=self.stdout) | |
297 return | |
298 except AttributeError: | |
299 pass | |
300 cmd.Cmd.do_help(self, arg) | |
301 | |
302 def __init__(self, *args, **kwargs): | |
303 cmd.Cmd.__init__(self, *args, **kwargs) | |
304 self.history = History() | |
305 self._init_parser() | |
306 self.pystate = {} | |
307 | |
308 def do_shortcuts(self, args): | |
309 """Lists single-key shortcuts available.""" | |
310 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in self.shortcuts.items()) | |
311 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result)) | |
312 | |
313 prefixParser = pyparsing.Empty() | |
314 commentGrammars = pyparsing.Or([pyparsing.pythonStyleComment, pyparsing.cStyleComment]) | |
315 commentGrammars.addParseAction(lambda x: '') | |
316 commentInProgress = ((pyparsing.White() | pyparsing.lineStart) + | |
317 pyparsing.Literal('/*') + pyparsing.SkipTo(pyparsing.stringEnd)) | |
318 # `blah/*` means `everything in directory `blah`, not comment | |
319 terminators = [';'] | |
320 blankLinesAllowed = False | |
321 multilineCommands = [] | |
322 | |
323 def _init_parser(self): | |
324 r''' | |
325 >>> c = Cmd() | |
326 >>> c.multilineCommands = ['multiline'] | |
327 >>> c.case_insensitive = True | |
328 >>> c._init_parser() | |
329 >>> print c.parser.parseString('').dump() | |
330 [] | |
331 >>> print c.parser.parseString('/* empty command */').dump() | |
332 [] | |
333 >>> print c.parser.parseString('plainword').dump() | |
334 ['plainword', ''] | |
335 - command: plainword | |
336 - statement: ['plainword', ''] | |
337 - command: plainword | |
338 >>> print c.parser.parseString('termbare;').dump() | |
339 ['termbare', '', ';', ''] | |
340 - command: termbare | |
341 - statement: ['termbare', '', ';'] | |
342 - command: termbare | |
343 - terminator: ; | |
344 - terminator: ; | |
345 >>> print c.parser.parseString('termbare; suffx').dump() | |
346 ['termbare', '', ';', 'suffx'] | |
347 - command: termbare | |
348 - statement: ['termbare', '', ';'] | |
349 - command: termbare | |
350 - terminator: ; | |
351 - suffix: suffx | |
352 - terminator: ; | |
353 >>> print c.parser.parseString('barecommand').dump() | |
354 ['barecommand', ''] | |
355 - command: barecommand | |
356 - statement: ['barecommand', ''] | |
357 - command: barecommand | |
358 >>> print c.parser.parseString('COMmand with args').dump() | |
359 ['command', 'with args'] | |
360 - args: with args | |
361 - command: command | |
362 - statement: ['command', 'with args'] | |
363 - args: with args | |
364 - command: command | |
365 >>> print c.parser.parseString('command with args and terminator; and suffix').dump() | |
366 ['command', 'with args and terminator', ';', 'and suffix'] | |
367 - args: with args and terminator | |
368 - command: command | |
369 - statement: ['command', 'with args and terminator', ';'] | |
370 - args: with args and terminator | |
371 - command: command | |
372 - terminator: ; | |
373 - suffix: and suffix | |
374 - terminator: ; | |
375 >>> print c.parser.parseString('simple | piped').dump() | |
376 ['simple', '', '|', ' piped'] | |
377 - command: simple | |
378 - pipeTo: piped | |
379 - statement: ['simple', ''] | |
380 - command: simple | |
381 >>> print c.parser.parseString('double-pipe || is not a pipe').dump() | |
382 ['double', '-pipe || is not a pipe'] | |
383 - args: -pipe || is not a pipe | |
384 - command: double | |
385 - statement: ['double', '-pipe || is not a pipe'] | |
386 - args: -pipe || is not a pipe | |
387 - command: double | |
388 >>> print c.parser.parseString('command with args, terminator;sufx | piped').dump() | |
389 ['command', 'with args, terminator', ';', 'sufx', '|', ' piped'] | |
390 - args: with args, terminator | |
391 - command: command | |
392 - pipeTo: piped | |
393 - statement: ['command', 'with args, terminator', ';'] | |
394 - args: with args, terminator | |
395 - command: command | |
396 - terminator: ; | |
397 - suffix: sufx | |
398 - terminator: ; | |
399 >>> print c.parser.parseString('output into > afile.txt').dump() | |
400 ['output', 'into', '>', 'afile.txt'] | |
401 - args: into | |
402 - command: output | |
403 - output: > | |
404 - outputTo: afile.txt | |
405 - statement: ['output', 'into'] | |
406 - args: into | |
407 - command: output | |
408 >>> print c.parser.parseString('output into;sufx | pipethrume plz > afile.txt').dump() | |
409 ['output', 'into', ';', 'sufx', '|', ' pipethrume plz', '>', 'afile.txt'] | |
410 - args: into | |
411 - command: output | |
412 - output: > | |
413 - outputTo: afile.txt | |
414 - pipeTo: pipethrume plz | |
415 - statement: ['output', 'into', ';'] | |
416 - args: into | |
417 - command: output | |
418 - terminator: ; | |
419 - suffix: sufx | |
420 - terminator: ; | |
421 >>> print c.parser.parseString('output to paste buffer >> ').dump() | |
422 ['output', 'to paste buffer', '>>', ''] | |
423 - args: to paste buffer | |
424 - command: output | |
425 - output: >> | |
426 - statement: ['output', 'to paste buffer'] | |
427 - args: to paste buffer | |
428 - command: output | |
429 >>> print c.parser.parseString('ignore the /* commented | > */ stuff;').dump() | |
430 ['ignore', 'the /* commented | > */ stuff', ';', ''] | |
431 - args: the /* commented | > */ stuff | |
432 - command: ignore | |
433 - statement: ['ignore', 'the /* commented | > */ stuff', ';'] | |
434 - args: the /* commented | > */ stuff | |
435 - command: ignore | |
436 - terminator: ; | |
437 - terminator: ; | |
438 >>> print c.parser.parseString('has > inside;').dump() | |
439 ['has', '> inside', ';', ''] | |
440 - args: > inside | |
441 - command: has | |
442 - statement: ['has', '> inside', ';'] | |
443 - args: > inside | |
444 - command: has | |
445 - terminator: ; | |
446 - terminator: ; | |
447 >>> print c.parser.parseString('multiline has > inside an unfinished command').dump() | |
448 ['multiline', ' has > inside an unfinished command'] | |
449 - multilineCommand: multiline | |
450 >>> print c.parser.parseString('multiline has > inside;').dump() | |
451 ['multiline', 'has > inside', ';', ''] | |
452 - args: has > inside | |
453 - multilineCommand: multiline | |
454 - statement: ['multiline', 'has > inside', ';'] | |
455 - args: has > inside | |
456 - multilineCommand: multiline | |
457 - terminator: ; | |
458 - terminator: ; | |
459 >>> print c.parser.parseString('multiline command /* with comment in progress;').dump() | |
460 ['multiline', ' command /* with comment in progress;'] | |
461 - multilineCommand: multiline | |
462 >>> print c.parser.parseString('multiline command /* with comment complete */ is done;').dump() | |
463 ['multiline', 'command /* with comment complete */ is done', ';', ''] | |
464 - args: command /* with comment complete */ is done | |
465 - multilineCommand: multiline | |
466 - statement: ['multiline', 'command /* with comment complete */ is done', ';'] | |
467 - args: command /* with comment complete */ is done | |
468 - multilineCommand: multiline | |
469 - terminator: ; | |
470 - terminator: ; | |
471 >>> print c.parser.parseString('multiline command ends\n\n').dump() | |
472 ['multiline', 'command ends', '\n', '\n'] | |
473 - args: command ends | |
474 - multilineCommand: multiline | |
475 - statement: ['multiline', 'command ends', '\n', '\n'] | |
476 - args: command ends | |
477 - multilineCommand: multiline | |
478 - terminator: ['\n', '\n'] | |
479 - terminator: ['\n', '\n'] | |
480 ''' | |
481 outputParser = (pyparsing.Literal('>>') | (pyparsing.WordStart() + '>') | pyparsing.Regex('[^=]>'))('output') | |
482 | |
483 terminatorParser = pyparsing.Or([(hasattr(t, 'parseString') and t) or pyparsing.Literal(t) for t in self.terminators])('terminator') | |
484 stringEnd = pyparsing.stringEnd ^ '\nEOF' | |
485 self.multilineCommand = pyparsing.Or([pyparsing.Keyword(c, caseless=self.case_insensitive) for c in self.multilineCommands])('multilineCommand') | |
486 oneLineCommand = (~self.multilineCommand + pyparsing.Word(self.legalChars))('command') | |
487 pipe = pyparsing.Keyword('|', identChars='|') | |
488 self.commentGrammars.ignore(pyparsing.quotedString).setParseAction(lambda x: '') | |
489 self.commentInProgress.ignore(pyparsing.quotedString).ignore(pyparsing.cStyleComment) | |
490 afterElements = \ | |
491 pyparsing.Optional(pipe + pyparsing.SkipTo(outputParser ^ stringEnd)('pipeTo')) + \ | |
492 pyparsing.Optional(outputParser + pyparsing.SkipTo(stringEnd).setParseAction(lambda x: x[0].strip())('outputTo')) | |
493 if self.case_insensitive: | |
494 self.multilineCommand.setParseAction(lambda x: x[0].lower()) | |
495 oneLineCommand.setParseAction(lambda x: x[0].lower()) | |
496 if self.blankLinesAllowed: | |
497 self.blankLineTerminationParser = pyparsing.NoMatch | |
498 else: | |
499 self.blankLineTerminator = (pyparsing.lineEnd + pyparsing.lineEnd)('terminator') | |
500 self.blankLineTerminator.setResultsName('terminator') | |
501 self.blankLineTerminationParser = ((self.multilineCommand ^ oneLineCommand) + pyparsing.SkipTo(self.blankLineTerminator).setParseAction(lambda x: x[0].strip())('args') + self.blankLineTerminator)('statement') | |
502 self.multilineParser = (((self.multilineCommand ^ oneLineCommand) + SkipToLast(terminatorParser).setParseAction(lambda x: x[0].strip())('args') + terminatorParser)('statement') + | |
503 pyparsing.SkipTo(outputParser ^ pipe ^ stringEnd).setParseAction(lambda x: x[0].strip())('suffix') + afterElements) | |
504 self.singleLineParser = ((oneLineCommand + pyparsing.SkipTo(terminatorParser ^ stringEnd ^ pipe ^ outputParser).setParseAction(lambda x:x[0].strip())('args'))('statement') + | |
505 pyparsing.Optional(terminatorParser) + afterElements) | |
506 #self.multilineParser = self.multilineParser.setResultsName('multilineParser') | |
507 #self.singleLineParser = self.singleLineParser.setResultsName('singleLineParser') | |
508 #self.blankLineTerminationParser = self.blankLineTerminationParser.setResultsName('blankLineTerminatorParser') | |
509 self.parser = ( | |
510 stringEnd | | |
511 self.prefixParser + self.multilineParser | | |
512 self.prefixParser + self.singleLineParser | | |
513 self.prefixParser + self.blankLineTerminationParser | | |
514 self.prefixParser + self.multilineCommand + pyparsing.SkipTo(stringEnd) | |
515 ) | |
516 self.parser.ignore(pyparsing.quotedString).ignore(self.commentGrammars).ignore(self.commentInProgress) | |
517 | |
518 inputMark = pyparsing.Literal('<') | |
519 inputMark.setParseAction(lambda x: '') | |
520 fileName = pyparsing.Word(self.legalChars + '/\\') | |
521 inputFrom = fileName('inputFrom') | |
522 inputFrom.setParseAction(replace_with_file_contents) | |
523 # a not-entirely-satisfactory way of distinguishing < as in "import from" from < | |
524 # as in "lesser than" | |
525 self.inputParser = inputMark + pyparsing.Optional(inputFrom) + pyparsing.Optional('>') + \ | |
526 pyparsing.Optional(fileName) + (pyparsing.stringEnd | '|') | |
527 self.inputParser.ignore(pyparsing.quotedString).ignore(self.commentGrammars).ignore(self.commentInProgress) | |
528 | |
529 def preparse(self, raw, **kwargs): | |
530 return raw | |
531 | |
532 def parsed(self, raw, **kwargs): | |
533 if isinstance(raw, ParsedString): | |
534 p = raw | |
535 else: | |
536 raw = self.preparse(raw, **kwargs) | |
537 s = self.inputParser.transformString(raw.lstrip()) | |
538 for (shortcut, expansion) in self.shortcuts.items(): | |
539 if s.lower().startswith(shortcut): | |
540 s = s.replace(shortcut, expansion + ' ', 1) | |
541 break | |
542 result = self.parser.parseString(s) | |
543 result['command'] = result.multilineCommand or result.command | |
544 result['raw'] = raw | |
545 result['clean'] = self.commentGrammars.transformString(result.args) | |
546 result['expanded'] = s | |
547 p = ParsedString(result.clean) | |
548 p.parsed = result | |
549 p.parser = self.parsed | |
550 for (key, val) in kwargs.items(): | |
551 p.parsed[key] = val | |
552 return p | |
553 | |
554 def postparsing_precmd(self, statement): | |
555 stop = 0 | |
556 return stop, statement | |
557 def postparsing_postcmd(self, stop): | |
558 return stop | |
559 def onecmd(self, line): | |
560 """Interpret the argument as though it had been typed in response | |
561 to the prompt. | |
562 | |
563 This may be overridden, but should not normally need to be; | |
564 see the precmd() and postcmd() methods for useful execution hooks. | |
565 The return value is a flag indicating whether interpretation of | |
566 commands by the interpreter should stop. | |
567 | |
568 This (`cmd2`) version of `onecmd` already override's `cmd`'s `onecmd`. | |
569 | |
570 """ | |
571 if not line: | |
572 return self.emptyline() | |
573 if not pyparsing.Or(self.commentGrammars).setParseAction(lambda x: '').transformString(line): | |
574 return 0 # command was empty except for comments | |
575 try: | |
576 statement = self.parsed(line) | |
577 while statement.parsed.multilineCommand and (statement.parsed.terminator == ''): | |
578 statement = '%s\n%s' % (statement.parsed.raw, | |
579 self.pseudo_raw_input(self.continuation_prompt)) | |
580 statement = self.parsed(statement) | |
581 except Exception, e: | |
582 print e | |
583 return 0 | |
584 | |
585 try: | |
586 (stop, statement) = self.postparsing_precmd(statement) | |
587 except Exception, e: | |
588 print str(e) | |
589 return 0 | |
590 if stop: | |
591 return self.postparsing_postcmd(stop) | |
592 | |
593 if not statement.parsed.command: | |
594 return self.postparsing_postcmd(stop=0) | |
595 | |
596 statekeeper = None | |
597 | |
598 if statement.parsed.pipeTo: | |
599 redirect = subprocess.Popen(statement.parsed.pipeTo, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
600 statekeeper = Statekeeper(self, ('stdout',)) | |
601 self.stdout = redirect.stdin | |
602 elif statement.parsed.output: | |
603 statekeeper = Statekeeper(self, ('stdout',)) | |
604 if statement.parsed.outputTo: | |
605 mode = 'w' | |
606 if statement.parsed.output == '>>': | |
607 mode = 'a' | |
608 try: | |
609 self.stdout = open(os.path.expanduser(statement.parsed.outputTo), mode) | |
610 except OSError, e: | |
611 print e | |
612 return self.postparsing_postcmd(stop=0) | |
613 else: | |
614 statekeeper = Statekeeper(self, ('stdout',)) | |
615 self.stdout = tempfile.TemporaryFile() | |
616 if statement.parsed.output == '>>': | |
617 self.stdout.write(getPasteBuffer()) | |
618 try: | |
619 # "heart" of the command, replace's cmd's onecmd() | |
620 self.lastcmd = statement.parsed.expanded | |
621 try: | |
622 func = getattr(self, 'do_' + statement.parsed.command) | |
623 except AttributeError: | |
624 func = None | |
625 if self.abbrev: # accept shortened versions of commands | |
237 | 626 funcs = [(fname, function) for (fname, function) in inspect.getmembers(self, inspect.ismethod) |
230 | 627 if fname.startswith('do_' + statement.parsed.command)] |
628 if len(funcs) == 1: | |
237 | 629 func = funcs[0][1] |
230 | 630 if not func: |
631 return self.postparsing_postcmd(self.default(statement)) | |
632 timestart = datetime.datetime.now() | |
633 stop = func(statement) | |
634 if self.timing: | |
635 print 'Elapsed: %s' % str(datetime.datetime.now() - timestart) | |
636 except Exception, e: | |
637 print e | |
638 try: | |
639 if statement.parsed.command not in self.excludeFromHistory: | |
640 self.history.append(statement.parsed.raw) | |
641 finally: | |
642 if statekeeper: | |
643 if statement.parsed.output and not statement.parsed.outputTo: | |
644 self.stdout.seek(0) | |
645 try: | |
646 writeToPasteBuffer(self.stdout.read()) | |
647 except Exception, e: | |
648 print str(e) | |
649 elif statement.parsed.pipeTo: | |
650 for result in redirect.communicate(): | |
651 statekeeper.stdout.write(result or '') | |
652 self.stdout.close() | |
653 statekeeper.restore() | |
654 | |
655 return self.postparsing_postcmd(stop) | |
656 | |
657 def pseudo_raw_input(self, prompt): | |
658 """copied from cmd's cmdloop; like raw_input, but accounts for changed stdin, stdout""" | |
659 | |
660 if self.use_rawinput: | |
661 try: | |
662 line = raw_input(prompt) | |
663 except EOFError: | |
664 line = 'EOF' | |
665 else: | |
666 self.stdout.write(prompt) | |
667 self.stdout.flush() | |
668 line = self.stdin.readline() | |
669 if not len(line): | |
670 line = 'EOF' | |
671 else: | |
672 if line[-1] == '\n': # this was always true in Cmd | |
673 line = line[:-1] | |
674 return line | |
675 | |
676 def cmdloop(self, intro=None): | |
677 """Repeatedly issue a prompt, accept input, parse an initial prefix | |
678 off the received input, and dispatch to action methods, passing them | |
679 the remainder of the line as argument. | |
680 """ | |
681 | |
682 # An almost perfect copy from Cmd; however, the pseudo_raw_input portion | |
683 # has been split out so that it can be called separately | |
684 | |
685 self.preloop() | |
686 if self.use_rawinput and self.completekey: | |
687 try: | |
688 import readline | |
689 self.old_completer = readline.get_completer() | |
690 readline.set_completer(self.complete) | |
691 readline.parse_and_bind(self.completekey+": complete") | |
692 except ImportError: | |
693 pass | |
694 try: | |
695 if intro is not None: | |
696 self.intro = intro | |
697 if self.intro: | |
698 self.stdout.write(str(self.intro)+"\n") | |
699 stop = None | |
700 while not stop: | |
701 if self.cmdqueue: | |
702 line = self.cmdqueue.pop(0) | |
703 else: | |
704 line = self.pseudo_raw_input(self.prompt) | |
705 if (self.echo) and (isinstance(self.stdin, file)): | |
706 self.stdout.write(line + '\n') | |
707 line = self.precmd(line) | |
708 stop = self.onecmd(line) | |
709 stop = self.postcmd(stop, line) | |
710 self.postloop() | |
711 finally: | |
712 if self.use_rawinput and self.completekey: | |
713 try: | |
714 import readline | |
715 readline.set_completer(self.old_completer) | |
716 except ImportError: | |
717 pass | |
718 return stop | |
719 | |
720 def do_EOF(self, arg): | |
721 return True | |
722 do_eof = do_EOF | |
723 | |
724 def showParam(self, param): | |
725 any_shown = False | |
726 param = param.strip().lower() | |
727 for p in self.settable: | |
728 if p.startswith(param): | |
729 val = getattr(self, p) | |
730 self.stdout.write('%s: %s\n' % (p, str(getattr(self, p)))) | |
731 any_shown = True | |
732 if not any_shown: | |
733 print "Parameter '%s' not supported (type 'show' for list of parameters)." % param | |
734 | |
735 def do_quit(self, arg): | |
736 return self._STOP_AND_EXIT | |
737 do_exit = do_quit | |
738 do_q = do_quit | |
739 | |
740 def do_show(self, arg): | |
741 '''Shows value of a parameter.''' | |
742 if arg.strip(): | |
743 self.showParam(arg) | |
744 else: | |
745 for param in self.settable: | |
746 self.showParam(param) | |
747 | |
748 def do_set(self, arg): | |
749 '''Sets a cmd2 parameter. Accepts abbreviated parameter names so long as there is no ambiguity. | |
750 Call without arguments for a list of settable parameters with their values.''' | |
751 try: | |
752 paramName, val = arg.split(None, 1) | |
753 paramName = paramName.strip().lower() | |
754 hits = [paramName in p for p in self.settable] | |
755 if hits.count(True) == 1: | |
756 paramName = self.settable[hits.index(True)] | |
757 currentVal = getattr(self, paramName) | |
758 if (val[0] == val[-1]) and val[0] in ("'", '"'): | |
759 val = val[1:-1] | |
760 else: | |
761 val = cast(currentVal, val) | |
762 setattr(self, paramName, val) | |
763 self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val)) | |
764 if currentVal != val: | |
765 try: | |
766 onchange_hook = getattr(self, '_onchange_%s' % paramName) | |
767 onchange_hook(old=currentVal, new=val) | |
768 except AttributeError: | |
769 pass | |
770 else: | |
771 self.do_show(paramName) | |
772 except (ValueError, AttributeError, NotSettableError), e: | |
773 self.do_show(arg) | |
774 | |
775 def do_pause(self, arg): | |
776 'Displays the specified text then waits for the user to press RETURN.' | |
777 raw_input(arg + '\n') | |
778 | |
779 def do_shell(self, arg): | |
780 'execute a command as if at the OS prompt.' | |
781 os.system(arg) | |
782 | |
231 | 783 def _attempt_py_command(self, arg): |
784 try: | |
785 result = eval(arg, self.pystate) | |
786 print repr(result) | |
787 except SyntaxError: | |
788 exec(arg, self.pystate) | |
789 return | |
790 | |
233 | 791 def do_py(self, arg): |
230 | 792 ''' |
793 py <command>: Executes a Python command. | |
241 | 794 py: Enters interactive Python mode; `Ctrl-D`, `quit()`, 'exit()` ends. |
795 Non-python commands can be issued with `cmd("your command")`. | |
230 | 796 ''' |
797 if arg.strip(): | |
235
78ad20c2eed0
py working better now; still needs a iscomplete=True on onecmd
catherine@dellzilla
parents:
234
diff
changeset
|
798 interp = InteractiveInterpreter(locals=self.pystate) |
233 | 799 interp.runcode(arg) |
230 | 800 else: |
235
78ad20c2eed0
py working better now; still needs a iscomplete=True on onecmd
catherine@dellzilla
parents:
234
diff
changeset
|
801 interp = MyInteractiveConsole(locals=self.pystate) |
233 | 802 def quit(): |
234 | 803 raise EmbeddedConsoleExit |
236 | 804 def onecmd(arg): |
805 return self.onecmd(arg + '\n') | |
233 | 806 self.pystate['quit'] = quit |
807 self.pystate['exit'] = quit | |
236 | 808 self.pystate[self.nonpythoncommand] = onecmd |
234 | 809 try: |
240 | 810 cprt = 'Type "help", "copyright", "credits" or "license" for more information.' |
811 interp.interact(banner= "Python %s on %s\n%s\n(%s)\n%s" % | |
812 (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__)) | |
235
78ad20c2eed0
py working better now; still needs a iscomplete=True on onecmd
catherine@dellzilla
parents:
234
diff
changeset
|
813 except EmbeddedConsoleExit: |
234 | 814 return |
233 | 815 |
230 | 816 def do_history(self, arg): |
817 """history [arg]: lists past commands issued | |
818 | |
819 no arg -> list all | |
820 arg is integer -> list one history item, by index | |
821 arg is string -> string search | |
822 arg is /enclosed in forward-slashes/ -> regular expression search | |
823 """ | |
824 if arg: | |
825 history = self.history.get(arg) | |
826 else: | |
827 history = self.history | |
828 for hi in history: | |
829 self.stdout.write(hi.pr()) | |
830 def last_matching(self, arg): | |
831 try: | |
832 if arg: | |
833 return self.history.get(arg)[-1] | |
834 else: | |
835 return self.history[-1] | |
836 except IndexError: | |
837 return None | |
838 def do_list(self, arg): | |
839 """list [arg]: lists last command issued | |
840 | |
841 no arg -> list absolute last | |
842 arg is integer -> list one history item, by index | |
843 - arg, arg - (integer) -> list up to or after #arg | |
844 arg is string -> list last command matching string search | |
845 arg is /enclosed in forward-slashes/ -> regular expression search | |
846 """ | |
847 try: | |
848 self.stdout.write(self.last_matching(arg).pr()) | |
849 except: | |
850 pass | |
851 do_hi = do_history | |
852 do_l = do_list | |
853 do_li = do_list | |
854 | |
855 def do_ed(self, arg): | |
856 """ed: edit most recent command in text editor | |
857 ed [N]: edit numbered command from history | |
858 ed [filename]: edit specified file name | |
859 | |
860 commands are run after editor is closed. | |
861 "set edit (program-name)" or set EDITOR environment variable | |
862 to control which editing program is used.""" | |
863 if not self.editor: | |
864 print "please use 'set editor' to specify your text editing program of choice." | |
865 return | |
866 filename = self.default_file_name | |
867 if arg: | |
868 try: | |
869 buffer = self.last_matching(int(arg)) | |
870 except ValueError: | |
871 filename = arg | |
872 buffer = '' | |
873 else: | |
874 buffer = self.history[-1] | |
875 | |
876 if buffer: | |
877 f = open(os.path.expanduser(filename), 'w') | |
878 f.write(buffer or '') | |
879 f.close() | |
880 | |
881 os.system('%s %s' % (self.editor, filename)) | |
882 self.do__load(filename) | |
883 do_edit = do_ed | |
884 | |
885 saveparser = (pyparsing.Optional(pyparsing.Word(pyparsing.nums)^'*')("idx") + | |
886 pyparsing.Optional(pyparsing.Word(legalChars + '/\\'))("fname") + | |
887 pyparsing.stringEnd) | |
888 def do_save(self, arg): | |
889 """`save [N] [filename.ext]` | |
890 Saves command from history to file. | |
891 N => Number of command (from history), or `*`; | |
892 most recent command if omitted""" | |
893 | |
894 try: | |
895 args = self.saveparser.parseString(arg) | |
896 except pyparsing.ParseException: | |
897 print self.do_save.__doc__ | |
898 return | |
899 fname = args.fname or self.default_file_name | |
900 if args.idx == '*': | |
901 saveme = '\n\n'.join(self.history[:]) | |
902 elif args.idx: | |
903 saveme = self.history[int(args.idx)-1] | |
904 else: | |
905 saveme = self.history[-1] | |
906 try: | |
907 f = open(os.path.expanduser(fname), 'w') | |
908 f.write(saveme) | |
909 f.close() | |
910 print 'Saved to %s' % (fname) | |
911 except Exception, e: | |
912 print 'Error saving %s: %s' % (fname, str(e)) | |
913 | |
914 urlre = re.compile('(https?://[-\\w\\./]+)') | |
915 def do_load(self, fname=None): | |
916 """Runs script of command(s) from a file or URL.""" | |
917 if fname is None: | |
918 fname = self.default_file_name | |
919 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt','continuation_prompt')) | |
920 try: | |
921 if isinstance(fname, file): | |
922 target = open(fname, 'r') | |
923 else: | |
924 match = self.urlre.match(fname) | |
925 if match: | |
926 target = urllib.urlopen(match.group(1)) | |
927 else: | |
928 fname = os.path.expanduser(fname) | |
929 try: | |
930 target = open(os.path.expanduser(fname), 'r') | |
931 except IOError, e: | |
932 target = open('%s.%s' % (os.path.expanduser(fname), | |
933 self.defaultExtension), 'r') | |
934 except IOError, e: | |
935 print 'Problem accessing script from %s: \n%s' % (fname, e) | |
936 keepstate.restore() | |
937 return | |
938 self.stdin = target | |
939 self.use_rawinput = False | |
940 self.prompt = self.continuation_prompt = '' | |
941 stop = self.cmdloop() | |
942 self.stdin.close() | |
943 keepstate.restore() | |
944 self.lastcmd = '' | |
945 return (stop == self._STOP_AND_EXIT) and self._STOP_AND_EXIT | |
946 do__load = do_load # avoid an unfortunate legacy use of do_load from sqlpython | |
947 | |
948 def do_run(self, arg): | |
949 """run [arg]: re-runs an earlier command | |
950 | |
951 no arg -> run most recent command | |
952 arg is integer -> run one history item, by index | |
953 arg is string -> run most recent command by string search | |
954 arg is /enclosed in forward-slashes/ -> run most recent by regex | |
955 """ | |
956 'run [N]: runs the SQL that was run N commands ago' | |
957 runme = self.last_matching(arg) | |
958 print runme | |
959 if runme: | |
960 runme = self.precmd(runme) | |
961 stop = self.onecmd(runme) | |
962 stop = self.postcmd(stop, runme) | |
963 do_r = do_run | |
964 | |
965 def fileimport(self, statement, source): | |
966 try: | |
967 f = open(os.path.expanduser(source)) | |
968 except IOError: | |
969 self.stdout.write("Couldn't read from file %s\n" % source) | |
970 return '' | |
971 data = f.read() | |
972 f.close() | |
973 return data | |
974 | |
975 class HistoryItem(str): | |
976 def __init__(self, instr): | |
977 str.__init__(self) | |
978 self.lowercase = self.lower() | |
979 self.idx = None | |
980 def pr(self): | |
981 return '-------------------------[%d]\n%s\n' % (self.idx, str(self)) | |
982 | |
983 class History(list): | |
984 rangeFrom = re.compile(r'^([\d])+\s*\-$') | |
985 def append(self, new): | |
986 new = HistoryItem(new) | |
987 list.append(self, new) | |
988 new.idx = len(self) | |
989 def extend(self, new): | |
990 for n in new: | |
991 self.append(n) | |
992 def get(self, getme): | |
993 try: | |
994 getme = int(getme) | |
995 if getme < 0: | |
996 return self[:(-1 * getme)] | |
997 else: | |
998 return [self[getme-1]] | |
999 except IndexError: | |
1000 return [] | |
1001 except (ValueError, TypeError): | |
1002 getme = getme.strip() | |
1003 mtch = self.rangeFrom.search(getme) | |
1004 if mtch: | |
1005 return self[(int(mtch.group(1))-1):] | |
1006 if getme.startswith(r'/') and getme.endswith(r'/'): | |
1007 finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE) | |
1008 def isin(hi): | |
1009 return finder.search(hi) | |
1010 else: | |
1011 def isin(hi): | |
1012 return (getme.lower() in hi.lowercase) | |
1013 return [itm for itm in self if isin(itm)] | |
1014 | |
1015 class NotSettableError(Exception): | |
1016 pass | |
1017 | |
1018 def cast(current, new): | |
1019 """Tries to force a new value into the same type as the current.""" | |
1020 typ = type(current) | |
1021 if typ == bool: | |
1022 try: | |
1023 return bool(int(new)) | |
1024 except ValueError, TypeError: | |
1025 pass | |
1026 try: | |
1027 new = new.lower() | |
1028 except: | |
1029 pass | |
1030 if (new=='on') or (new[0] in ('y','t')): | |
1031 return True | |
1032 if (new=='off') or (new[0] in ('n','f')): | |
1033 return False | |
1034 else: | |
1035 try: | |
1036 return typ(new) | |
1037 except: | |
1038 pass | |
1039 print "Problem setting parameter (now %s) to %s; incorrect type?" % (current, new) | |
1040 return current | |
1041 | |
1042 class Statekeeper(object): | |
1043 def __init__(self, obj, attribs): | |
1044 self.obj = obj | |
1045 self.attribs = attribs | |
1046 self.save() | |
1047 def save(self): | |
1048 for attrib in self.attribs: | |
1049 setattr(self, attrib, getattr(self.obj, attrib)) | |
1050 def restore(self): | |
1051 for attrib in self.attribs: | |
1052 setattr(self.obj, attrib, getattr(self, attrib)) | |
1053 | |
1054 class Borg(object): | |
1055 '''All instances of any Borg subclass will share state. | |
1056 from Python Cookbook, 2nd Ed., recipe 6.16''' | |
1057 _shared_state = {} | |
1058 def __new__(cls, *a, **k): | |
1059 obj = object.__new__(cls, *a, **k) | |
1060 obj.__dict__ = cls._shared_state | |
1061 return obj | |
1062 | |
1063 class OutputTrap(Borg): | |
1064 '''Instantiate an OutputTrap to divert/capture ALL stdout output. For use in unit testing. | |
1065 Call `tearDown()` to return to normal output.''' | |
1066 def __init__(self): | |
1067 self.old_stdout = sys.stdout | |
1068 self.trap = tempfile.TemporaryFile() | |
1069 sys.stdout = self.trap | |
1070 def read(self): | |
1071 self.trap.seek(0) | |
1072 result = self.trap.read() | |
1073 self.trap.truncate(0) | |
1074 return result.strip('\x00') | |
1075 def tearDown(self): | |
1076 sys.stdout = self.old_stdout | |
1077 | |
1078 class Cmd2TestCase(unittest.TestCase): | |
1079 '''Subclass this, setting CmdApp and transcriptFileName, to make a unittest.TestCase class | |
1080 that will execute the commands in transcriptFileName and expect the results shown. | |
1081 See example.py''' | |
1082 CmdApp = None | |
1083 transcriptFileName = '' | |
1084 def setUp(self): | |
1085 if self.CmdApp: | |
1086 self.outputTrap = OutputTrap() | |
1087 self.cmdapp = self.CmdApp() | |
1088 try: | |
1089 tfile = open(os.path.expanduser(self.transcriptFileName)) | |
1090 self.transcript = iter(tfile.readlines()) | |
1091 tfile.close() | |
1092 except IOError: | |
1093 self.transcript = [] | |
1094 def assertEqualEnough(self, got, expected, message): | |
1095 got = got.strip().splitlines() | |
1096 expected = expected.strip().splitlines() | |
1097 self.assertEqual(len(got), len(expected), message) | |
1098 for (linegot, lineexpected) in zip(got, expected): | |
1099 matchme = re.escape(lineexpected.strip()).replace('\\*', '.*'). \ | |
1100 replace('\\ ', ' ') | |
1101 self.assert_(re.match(matchme, linegot.strip()), message) | |
1102 def testall(self): | |
1103 if self.CmdApp: | |
1104 lineNum = 0 | |
1105 try: | |
1106 line = self.transcript.next() | |
1107 while True: | |
1108 while not line.startswith(self.cmdapp.prompt): | |
1109 line = self.transcript.next() | |
1110 command = [line[len(self.cmdapp.prompt):]] | |
1111 line = self.transcript.next() | |
1112 while line.startswith(self.cmdapp.continuation_prompt): | |
1113 command.append(line[len(self.cmdapp.continuation_prompt):]) | |
1114 line = self.transcript.next() | |
1115 command = ''.join(command) | |
1116 self.cmdapp.onecmd(command) | |
1117 result = self.outputTrap.read() | |
1118 if line.startswith(self.cmdapp.prompt): | |
1119 self.assertEqualEnough(result.strip(), '', | |
1120 '\nFile %s, line %d\nCommand was:\n%s\nExpected: (nothing) \nGot:\n%s\n' % | |
1121 (self.transcriptFileName, lineNum, command, result)) | |
1122 continue | |
1123 expected = [] | |
1124 while not line.startswith(self.cmdapp.prompt): | |
1125 expected.append(line) | |
1126 line = self.transcript.next() | |
1127 expected = ''.join(expected) | |
1128 self.assertEqualEnough(expected.strip(), result.strip(), | |
1129 '\nFile %s, line %d\nCommand was:\n%s\nExpected:\n%s\nGot:\n%s\n' % | |
1130 (self.transcriptFileName, lineNum, command, expected, result)) | |
1131 # this needs to account for a line-by-line strip()ping | |
1132 except StopIteration: | |
1133 pass | |
1134 # catch the final output? | |
1135 def tearDown(self): | |
1136 if self.CmdApp: | |
1137 self.outputTrap.tearDown() | |
1138 | |
1139 if __name__ == '__main__': | |
1140 doctest.testmod(optionflags = doctest.NORMALIZE_WHITESPACE) | |
1141 #c = Cmd() |