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