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