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