Mercurial > python-cmd2
annotate cmd2.py @ 248:575652efb3d8
aha - I think I know why comment-in-progress parse failing
author | catherine@Elli.myhome.westell.com |
---|---|
date | Mon, 30 Mar 2009 12:56:08 -0400 |
parents | 3db4166a54ce |
children | 55a12d77a4fa |
rev | line source |
---|---|
230 | 1 """Variant on standard library's cmd with extra features. |
2 | |
3 To use, simply import cmd2.Cmd instead of cmd.Cmd; use precisely as though you | |
4 were using the standard library's cmd, while enjoying the extra features. | |
5 | |
6 Searchable command history (commands: "hi", "li", "run") | |
7 Load commands from file, save to file, edit commands in file | |
8 Multi-line commands | |
9 Case-insensitive commands | |
10 Special-character shortcut commands (beyond cmd's "@" and "!") | |
11 Settable environment parameters | |
12 Optional _onchange_{paramname} called when environment parameter changes | |
13 Parsing commands with `optparse` options (flags) | |
14 Redirection to file with >, >>; input from file with < | |
15 Easy transcript-based testing of applications (see example/example.py) | |
16 | |
17 Note that redirection with > and | will only work if `self.stdout.write()` | |
18 is used in place of `print`. The standard library's `cmd` module is | |
19 written to use `self.stdout.write()`, | |
20 | |
21 - Catherine Devlin, Jan 03 2008 - catherinedevlin.blogspot.com | |
22 | |
23 mercurial repository at http://www.assembla.com/wiki/show/python-cmd2 | |
24 CHANGES: | |
25 As of 0.3.0, options should be specified as `optparse` options. See README.txt. | |
26 flagReader.py options are still supported for backward compatibility | |
27 """ | |
28 import cmd, re, os, sys, optparse, subprocess, tempfile, pyparsing, doctest | |
247
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
29 import unittest, string, datetime, urllib |
235
78ad20c2eed0
py working better now; still needs a iscomplete=True on onecmd
catherine@dellzilla
parents:
234
diff
changeset
|
30 from code import InteractiveConsole, InteractiveInterpreter, softspace |
230 | 31 from optparse import make_option |
248
575652efb3d8
aha - I think I know why comment-in-progress parse failing
catherine@Elli.myhome.westell.com
parents:
247
diff
changeset
|
32 __version__ = '0.5.1' |
230 | 33 |
34 class OptionParser(optparse.OptionParser): | |
35 def exit(self, status=0, msg=None): | |
36 self.values._exit = True | |
37 if msg: | |
38 print msg | |
39 | |
40 def print_help(self, *args, **kwargs): | |
41 # now, I need to call help of the calling function. Hmm. | |
42 try: | |
43 print self._func.__doc__ | |
44 except AttributeError: | |
45 pass | |
46 optparse.OptionParser.print_help(self, *args, **kwargs) | |
47 | |
48 def error(self, msg): | |
49 """error(msg : string) | |
50 | |
51 Print a usage message incorporating 'msg' to stderr and exit. | |
52 If you override this in a subclass, it should not return -- it | |
53 should either exit or raise an exception. | |
54 """ | |
55 raise | |
56 | |
57 def remainingArgs(oldArgs, newArgList): | |
58 ''' | |
59 >>> remainingArgs('-f bar bar cow', ['bar', 'cow']) | |
60 'bar cow' | |
61 ''' | |
62 pattern = '\s+'.join(re.escape(a) for a in newArgList) + '\s*$' | |
63 matchObj = re.search(pattern, oldArgs) | |
64 return oldArgs[matchObj.start():] | |
65 | |
66 def options(option_list): | |
67 def option_setup(func): | |
68 optionParser = OptionParser() | |
69 for opt in option_list: | |
70 optionParser.add_option(opt) | |
71 optionParser.set_usage("%s [options] arg" % func.__name__.strip('do_')) | |
72 optionParser._func = func | |
73 def newFunc(instance, arg): | |
74 try: | |
75 opts, newArgList = optionParser.parse_args(arg.split()) # doesn't understand quoted strings shouldn't be dissected! | |
76 newArgs = remainingArgs(arg, newArgList) # should it permit flags after args? | |
77 except (optparse.OptionValueError, optparse.BadOptionError, | |
78 optparse.OptionError, optparse.AmbiguousOptionError, | |
79 optparse.OptionConflictError), e: | |
80 print e | |
81 optionParser.print_help() | |
82 return | |
83 if hasattr(opts, '_exit'): | |
84 return None | |
85 if hasattr(arg, 'parser'): | |
86 terminator = arg.parsed.terminator | |
87 try: | |
88 if arg.parsed.terminator[0] == '\n': | |
89 terminator = arg.parsed.terminator[0] | |
90 except IndexError: | |
91 pass | |
92 arg = arg.parser('%s %s%s%s' % (arg.parsed.command, newArgs, | |
93 terminator, arg.parsed.suffix)) | |
94 else: | |
95 arg = newArgs | |
96 result = func(instance, arg, opts) | |
97 return result | |
98 newFunc.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help()) | |
99 return newFunc | |
100 return option_setup | |
101 | |
102 class PasteBufferError(EnvironmentError): | |
103 if sys.platform[:3] == 'win': | |
104 errmsg = """Redirecting to or from paste buffer requires pywin32 | |
105 to be installed on operating system. | |
106 Download from http://sourceforge.net/projects/pywin32/""" | |
107 else: | |
108 errmsg = """Redirecting to or from paste buffer requires xclip | |
109 to be installed on operating system. | |
110 On Debian/Ubuntu, 'sudo apt-get install xclip' will install it.""" | |
111 def __init__(self): | |
112 Exception.__init__(self, self.errmsg) | |
113 | |
114 '''check here if functions exist; otherwise, stub out''' | |
115 pastebufferr = """Redirecting to or from paste buffer requires %s | |
116 to be installed on operating system. | |
117 %s""" | |
118 if subprocess.mswindows: | |
119 try: | |
120 import win32clipboard | |
121 def getPasteBuffer(): | |
122 win32clipboard.OpenClipboard(0) | |
123 try: | |
124 result = win32clipboard.GetClipboardData() | |
125 except TypeError: | |
126 result = '' #non-text | |
127 win32clipboard.CloseClipboard() | |
128 return result | |
129 def writeToPasteBuffer(txt): | |
130 win32clipboard.OpenClipboard(0) | |
131 win32clipboard.EmptyClipboard() | |
132 win32clipboard.SetClipboardText(txt) | |
133 win32clipboard.CloseClipboard() | |
134 except ImportError: | |
135 def getPasteBuffer(*args): | |
136 raise OSError, pastebufferr % ('pywin32', 'Download from http://sourceforge.net/projects/pywin32/') | |
137 setPasteBuffer = getPasteBuffer | |
138 else: | |
139 can_clip = False | |
140 try: | |
141 subprocess.check_call('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
142 can_clip = True | |
143 except AttributeError: # check_call not defined, Python < 2.5 | |
144 teststring = 'Testing for presence of xclip.' | |
145 xclipproc = subprocess.Popen('xclip -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
146 xclipproc.stdin.write(teststring) | |
147 xclipproc.stdin.close() | |
148 xclipproc = subprocess.Popen('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
149 if xclipproc.stdout.read() == teststring: | |
150 can_clip = True | |
151 except (subprocess.CalledProcessError, OSError, IOError): | |
152 pass | |
153 if can_clip: | |
154 def getPasteBuffer(): | |
155 xclipproc = subprocess.Popen('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
156 return xclipproc.stdout.read() | |
157 def writeToPasteBuffer(txt): | |
158 xclipproc = subprocess.Popen('xclip -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
159 xclipproc.stdin.write(txt) | |
160 xclipproc.stdin.close() | |
161 # but we want it in both the "primary" and "mouse" clipboards | |
162 xclipproc = subprocess.Popen('xclip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
163 xclipproc.stdin.write(txt) | |
164 xclipproc.stdin.close() | |
165 else: | |
166 def getPasteBuffer(*args): | |
167 raise OSError, pastebufferr % ('xclip', 'On Debian/Ubuntu, install with "sudo apt-get install xclip"') | |
168 setPasteBuffer = getPasteBuffer | |
169 writeToPasteBuffer = getPasteBuffer | |
170 | |
171 pyparsing.ParserElement.setDefaultWhitespaceChars(' \t') | |
172 | |
173 class ParsedString(str): | |
174 pass | |
175 | |
176 class SkipToLast(pyparsing.SkipTo): | |
177 def parseImpl( self, instring, loc, doActions=True ): | |
178 resultStore = [] | |
179 startLoc = loc | |
180 instrlen = len(instring) | |
181 expr = self.expr | |
182 failParse = False | |
183 while loc <= instrlen: | |
184 try: | |
185 if self.failOn: | |
186 failParse = True | |
187 self.failOn.tryParse(instring, loc) | |
188 failParse = False | |
189 loc = expr._skipIgnorables( instring, loc ) | |
190 expr._parse( instring, loc, doActions=False, callPreParse=False ) | |
191 skipText = instring[startLoc:loc] | |
192 if self.includeMatch: | |
193 loc,mat = expr._parse(instring,loc,doActions,callPreParse=False) | |
194 if mat: | |
195 skipRes = ParseResults( skipText ) | |
196 skipRes += mat | |
197 resultStore.append((loc, [ skipRes ])) | |
198 else: | |
199 resultStore,append((loc, [ skipText ])) | |
200 else: | |
201 resultStore.append((loc, [ skipText ])) | |
202 loc += 1 | |
203 except (pyparsing.ParseException,IndexError): | |
204 if failParse: | |
205 raise | |
206 else: | |
207 loc += 1 | |
208 if resultStore: | |
209 return resultStore[-1] | |
210 else: | |
211 exc = self.myException | |
212 exc.loc = loc | |
213 exc.pstr = instring | |
214 raise exc | |
215 | |
216 def replace_with_file_contents(fname): | |
217 if fname: | |
218 try: | |
219 result = open(os.path.expanduser(fname[0])).read() | |
220 except IOError: | |
221 result = '< %s' % fname[0] # wasn't a file after all | |
222 else: | |
223 result = getPasteBuffer() | |
233 | 224 return result |
225 | |
234 | 226 class EmbeddedConsoleExit(Exception): |
227 pass | |
228 | |
235
78ad20c2eed0
py working better now; still needs a iscomplete=True on onecmd
catherine@dellzilla
parents:
234
diff
changeset
|
229 class MyInteractiveConsole(InteractiveConsole): |
234 | 230 def runcode(self, code): |
231 """Execute a code object. | |
232 | |
233 When an exception occurs, self.showtraceback() is called to | |
234 display a traceback. All exceptions are caught except | |
235 SystemExit, which is reraised. | |
236 | |
237 A note about KeyboardInterrupt: this exception may occur | |
238 elsewhere in this code, and may not always be caught. The | |
239 caller should be prepared to deal with it. | |
240 | |
241 Copied directly from code.InteractiveInterpreter, except for | |
242 EmbeddedConsoleExit exceptions. | |
243 """ | |
244 try: | |
245 exec code in self.locals | |
246 except (SystemExit, EmbeddedConsoleExit): | |
247 raise | |
248 except: | |
249 self.showtraceback() | |
250 else: | |
235
78ad20c2eed0
py working better now; still needs a iscomplete=True on onecmd
catherine@dellzilla
parents:
234
diff
changeset
|
251 if softspace(sys.stdout, 0): |
234 | 252 print |
253 | |
230 | 254 class Cmd(cmd.Cmd): |
255 echo = False | |
256 case_insensitive = True | |
257 continuation_prompt = '> ' | |
258 timing = False | |
259 legalChars = '!#$%.:?@_' + pyparsing.alphanums + pyparsing.alphas8bit # make sure your terminators are not in here! | |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
260 shortcuts = {'?': 'help', '!': 'shell', '@': 'load', '@@': '_relative_load'} |
230 | 261 excludeFromHistory = '''run r list l history hi ed edit li eof'''.split() |
262 noSpecialParse = 'set ed edit exit'.split() | |
263 defaultExtension = 'txt' | |
264 default_file_name = 'command.txt' | |
265 abbrev = True | |
233 | 266 nonpythoncommand = 'cmd' |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
267 current_script_dir = None |
245 | 268 reserved_words = [] |
230 | 269 settable = ['prompt', 'continuation_prompt', 'default_file_name', 'editor', |
245 | 270 'case_insensitive', 'echo', 'timing', 'abbrev'] |
230 | 271 settable.sort() |
272 | |
273 editor = os.environ.get('EDITOR') | |
274 _STOP_AND_EXIT = 2 | |
275 if not editor: | |
276 if sys.platform[:3] == 'win': | |
277 editor = 'notepad' | |
278 else: | |
279 for editor in ['gedit', 'kate', 'vim', 'emacs', 'nano', 'pico']: | |
280 if not os.system('which %s' % (editor)): | |
281 break | |
282 | |
283 def do_cmdenvironment(self, args): | |
284 '''Summary report of interactive parameters.''' | |
285 self.stdout.write(""" | |
286 Commands are %(casesensitive)scase-sensitive. | |
287 Commands may be terminated with: %(terminators)s | |
237 | 288 Settable parameters: %(settable)s\n""" % \ |
230 | 289 { 'casesensitive': (self.case_insensitive and 'not ') or '', |
290 'terminators': str(self.terminators), | |
291 'settable': ' '.join(self.settable) | |
292 }) | |
293 | |
294 def do_help(self, arg): | |
247
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
295 funcname = self.func_named(arg) |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
296 if funcname: |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
297 fn = getattr(self, funcname) |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
298 try: |
230 | 299 fn.optionParser.print_help(file=self.stdout) |
247
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
300 except AttributeError: |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
301 cmd.Cmd.do_help(self, funcname[3:]) |
230 | 302 |
303 def __init__(self, *args, **kwargs): | |
304 cmd.Cmd.__init__(self, *args, **kwargs) | |
305 self.history = History() | |
306 self._init_parser() | |
307 self.pystate = {} | |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
308 self.shortcuts = sorted(self.shortcuts.items(), reverse=True) |
247
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
309 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
|
310 if fname.startswith('do_')] |
230 | 311 def do_shortcuts(self, args): |
312 """Lists single-key shortcuts available.""" | |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
313 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts)) |
230 | 314 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result)) |
315 | |
316 prefixParser = pyparsing.Empty() | |
317 commentGrammars = pyparsing.Or([pyparsing.pythonStyleComment, pyparsing.cStyleComment]) | |
318 commentGrammars.addParseAction(lambda x: '') | |
319 commentInProgress = ((pyparsing.White() | pyparsing.lineStart) + | |
320 pyparsing.Literal('/*') + pyparsing.SkipTo(pyparsing.stringEnd)) | |
321 # `blah/*` means `everything in directory `blah`, not comment | |
322 terminators = [';'] | |
323 blankLinesAllowed = False | |
324 multilineCommands = [] | |
325 | |
326 def _init_parser(self): | |
327 r''' | |
328 >>> c = Cmd() | |
329 >>> c.multilineCommands = ['multiline'] | |
330 >>> c.case_insensitive = True | |
331 >>> c._init_parser() | |
332 >>> print c.parser.parseString('').dump() | |
333 [] | |
334 >>> print c.parser.parseString('/* empty command */').dump() | |
335 [] | |
336 >>> print c.parser.parseString('plainword').dump() | |
337 ['plainword', ''] | |
338 - command: plainword | |
339 - statement: ['plainword', ''] | |
340 - command: plainword | |
341 >>> print c.parser.parseString('termbare;').dump() | |
342 ['termbare', '', ';', ''] | |
343 - command: termbare | |
344 - statement: ['termbare', '', ';'] | |
345 - command: termbare | |
346 - terminator: ; | |
347 - terminator: ; | |
348 >>> print c.parser.parseString('termbare; suffx').dump() | |
349 ['termbare', '', ';', 'suffx'] | |
350 - command: termbare | |
351 - statement: ['termbare', '', ';'] | |
352 - command: termbare | |
353 - terminator: ; | |
354 - suffix: suffx | |
355 - terminator: ; | |
356 >>> print c.parser.parseString('barecommand').dump() | |
357 ['barecommand', ''] | |
358 - command: barecommand | |
359 - statement: ['barecommand', ''] | |
360 - command: barecommand | |
361 >>> print c.parser.parseString('COMmand with args').dump() | |
362 ['command', 'with args'] | |
363 - args: with args | |
364 - command: command | |
365 - statement: ['command', 'with args'] | |
366 - args: with args | |
367 - command: command | |
368 >>> print c.parser.parseString('command with args and terminator; and suffix').dump() | |
369 ['command', 'with args and terminator', ';', 'and suffix'] | |
370 - args: with args and terminator | |
371 - command: command | |
372 - statement: ['command', 'with args and terminator', ';'] | |
373 - args: with args and terminator | |
374 - command: command | |
375 - terminator: ; | |
376 - suffix: and suffix | |
377 - terminator: ; | |
378 >>> print c.parser.parseString('simple | piped').dump() | |
379 ['simple', '', '|', ' piped'] | |
380 - command: simple | |
381 - pipeTo: piped | |
382 - statement: ['simple', ''] | |
383 - command: simple | |
384 >>> print c.parser.parseString('double-pipe || is not a pipe').dump() | |
385 ['double', '-pipe || is not a pipe'] | |
386 - args: -pipe || is not a pipe | |
387 - command: double | |
388 - statement: ['double', '-pipe || is not a pipe'] | |
389 - args: -pipe || is not a pipe | |
390 - command: double | |
391 >>> print c.parser.parseString('command with args, terminator;sufx | piped').dump() | |
392 ['command', 'with args, terminator', ';', 'sufx', '|', ' piped'] | |
393 - args: with args, terminator | |
394 - command: command | |
395 - pipeTo: piped | |
396 - statement: ['command', 'with args, terminator', ';'] | |
397 - args: with args, terminator | |
398 - command: command | |
399 - terminator: ; | |
400 - suffix: sufx | |
401 - terminator: ; | |
402 >>> print c.parser.parseString('output into > afile.txt').dump() | |
403 ['output', 'into', '>', 'afile.txt'] | |
404 - args: into | |
405 - command: output | |
406 - output: > | |
407 - outputTo: afile.txt | |
408 - statement: ['output', 'into'] | |
409 - args: into | |
410 - command: output | |
411 >>> print c.parser.parseString('output into;sufx | pipethrume plz > afile.txt').dump() | |
412 ['output', 'into', ';', 'sufx', '|', ' pipethrume plz', '>', 'afile.txt'] | |
413 - args: into | |
414 - command: output | |
415 - output: > | |
416 - outputTo: afile.txt | |
417 - pipeTo: pipethrume plz | |
418 - statement: ['output', 'into', ';'] | |
419 - args: into | |
420 - command: output | |
421 - terminator: ; | |
422 - suffix: sufx | |
423 - terminator: ; | |
424 >>> print c.parser.parseString('output to paste buffer >> ').dump() | |
425 ['output', 'to paste buffer', '>>', ''] | |
426 - args: to paste buffer | |
427 - command: output | |
428 - output: >> | |
429 - statement: ['output', 'to paste buffer'] | |
430 - args: to paste buffer | |
431 - command: output | |
432 >>> print c.parser.parseString('ignore the /* commented | > */ stuff;').dump() | |
433 ['ignore', 'the /* commented | > */ stuff', ';', ''] | |
434 - args: the /* commented | > */ stuff | |
435 - command: ignore | |
436 - statement: ['ignore', 'the /* commented | > */ stuff', ';'] | |
437 - args: the /* commented | > */ stuff | |
438 - command: ignore | |
439 - terminator: ; | |
440 - terminator: ; | |
441 >>> print c.parser.parseString('has > inside;').dump() | |
442 ['has', '> inside', ';', ''] | |
443 - args: > inside | |
444 - command: has | |
445 - statement: ['has', '> inside', ';'] | |
446 - args: > inside | |
447 - command: has | |
448 - terminator: ; | |
449 - terminator: ; | |
450 >>> print c.parser.parseString('multiline has > inside an unfinished command').dump() | |
451 ['multiline', ' has > inside an unfinished command'] | |
452 - multilineCommand: multiline | |
453 >>> print c.parser.parseString('multiline has > inside;').dump() | |
454 ['multiline', 'has > inside', ';', ''] | |
455 - args: has > inside | |
456 - multilineCommand: multiline | |
457 - statement: ['multiline', 'has > inside', ';'] | |
458 - args: has > inside | |
459 - multilineCommand: multiline | |
460 - terminator: ; | |
461 - terminator: ; | |
462 >>> print c.parser.parseString('multiline command /* with comment in progress;').dump() | |
463 ['multiline', ' command /* with comment in progress;'] | |
464 - multilineCommand: multiline | |
465 >>> print c.parser.parseString('multiline command /* with comment complete */ is done;').dump() | |
466 ['multiline', 'command /* with comment complete */ is done', ';', ''] | |
467 - args: command /* with comment complete */ is done | |
468 - multilineCommand: multiline | |
469 - statement: ['multiline', 'command /* with comment complete */ is done', ';'] | |
470 - args: command /* with comment complete */ is done | |
471 - multilineCommand: multiline | |
472 - terminator: ; | |
473 - terminator: ; | |
474 >>> print c.parser.parseString('multiline command ends\n\n').dump() | |
475 ['multiline', 'command ends', '\n', '\n'] | |
476 - args: command ends | |
477 - multilineCommand: multiline | |
478 - statement: ['multiline', 'command ends', '\n', '\n'] | |
479 - args: command ends | |
480 - multilineCommand: multiline | |
481 - terminator: ['\n', '\n'] | |
482 - terminator: ['\n', '\n'] | |
483 ''' | |
484 outputParser = (pyparsing.Literal('>>') | (pyparsing.WordStart() + '>') | pyparsing.Regex('[^=]>'))('output') | |
485 | |
486 terminatorParser = pyparsing.Or([(hasattr(t, 'parseString') and t) or pyparsing.Literal(t) for t in self.terminators])('terminator') | |
487 stringEnd = pyparsing.stringEnd ^ '\nEOF' | |
488 self.multilineCommand = pyparsing.Or([pyparsing.Keyword(c, caseless=self.case_insensitive) for c in self.multilineCommands])('multilineCommand') | |
489 oneLineCommand = (~self.multilineCommand + pyparsing.Word(self.legalChars))('command') | |
490 pipe = pyparsing.Keyword('|', identChars='|') | |
491 self.commentGrammars.ignore(pyparsing.quotedString).setParseAction(lambda x: '') | |
492 self.commentInProgress.ignore(pyparsing.quotedString).ignore(pyparsing.cStyleComment) | |
493 afterElements = \ | |
494 pyparsing.Optional(pipe + pyparsing.SkipTo(outputParser ^ stringEnd)('pipeTo')) + \ | |
495 pyparsing.Optional(outputParser + pyparsing.SkipTo(stringEnd).setParseAction(lambda x: x[0].strip())('outputTo')) | |
496 if self.case_insensitive: | |
497 self.multilineCommand.setParseAction(lambda x: x[0].lower()) | |
498 oneLineCommand.setParseAction(lambda x: x[0].lower()) | |
499 if self.blankLinesAllowed: | |
500 self.blankLineTerminationParser = pyparsing.NoMatch | |
501 else: | |
502 self.blankLineTerminator = (pyparsing.lineEnd + pyparsing.lineEnd)('terminator') | |
503 self.blankLineTerminator.setResultsName('terminator') | |
504 self.blankLineTerminationParser = ((self.multilineCommand ^ oneLineCommand) + pyparsing.SkipTo(self.blankLineTerminator).setParseAction(lambda x: x[0].strip())('args') + self.blankLineTerminator)('statement') | |
505 self.multilineParser = (((self.multilineCommand ^ oneLineCommand) + SkipToLast(terminatorParser).setParseAction(lambda x: x[0].strip())('args') + terminatorParser)('statement') + | |
506 pyparsing.SkipTo(outputParser ^ pipe ^ stringEnd).setParseAction(lambda x: x[0].strip())('suffix') + afterElements) | |
507 self.singleLineParser = ((oneLineCommand + pyparsing.SkipTo(terminatorParser ^ stringEnd ^ pipe ^ outputParser).setParseAction(lambda x:x[0].strip())('args'))('statement') + | |
508 pyparsing.Optional(terminatorParser) + afterElements) | |
248
575652efb3d8
aha - I think I know why comment-in-progress parse failing
catherine@Elli.myhome.westell.com
parents:
247
diff
changeset
|
509 self.multilineParser = self.multilineParser.setResultsName('multilineParser') |
575652efb3d8
aha - I think I know why comment-in-progress parse failing
catherine@Elli.myhome.westell.com
parents:
247
diff
changeset
|
510 self.singleLineParser = self.singleLineParser.setResultsName('singleLineParser') |
575652efb3d8
aha - I think I know why comment-in-progress parse failing
catherine@Elli.myhome.westell.com
parents:
247
diff
changeset
|
511 self.blankLineTerminationParser = self.blankLineTerminationParser.setResultsName('blankLineTerminatorParser') |
230 | 512 self.parser = ( |
513 stringEnd | | |
514 self.prefixParser + self.multilineParser | | |
515 self.prefixParser + self.singleLineParser | | |
516 self.prefixParser + self.blankLineTerminationParser | | |
517 self.prefixParser + self.multilineCommand + pyparsing.SkipTo(stringEnd) | |
518 ) | |
519 self.parser.ignore(pyparsing.quotedString).ignore(self.commentGrammars).ignore(self.commentInProgress) | |
520 | |
521 inputMark = pyparsing.Literal('<') | |
522 inputMark.setParseAction(lambda x: '') | |
523 fileName = pyparsing.Word(self.legalChars + '/\\') | |
524 inputFrom = fileName('inputFrom') | |
525 inputFrom.setParseAction(replace_with_file_contents) | |
526 # a not-entirely-satisfactory way of distinguishing < as in "import from" from < | |
527 # as in "lesser than" | |
528 self.inputParser = inputMark + pyparsing.Optional(inputFrom) + pyparsing.Optional('>') + \ | |
529 pyparsing.Optional(fileName) + (pyparsing.stringEnd | '|') | |
530 self.inputParser.ignore(pyparsing.quotedString).ignore(self.commentGrammars).ignore(self.commentInProgress) | |
531 | |
532 def preparse(self, raw, **kwargs): | |
533 return raw | |
534 | |
535 def parsed(self, raw, **kwargs): | |
536 if isinstance(raw, ParsedString): | |
537 p = raw | |
538 else: | |
539 raw = self.preparse(raw, **kwargs) | |
540 s = self.inputParser.transformString(raw.lstrip()) | |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
541 for (shortcut, expansion) in self.shortcuts: |
230 | 542 if s.lower().startswith(shortcut): |
543 s = s.replace(shortcut, expansion + ' ', 1) | |
544 break | |
545 result = self.parser.parseString(s) | |
546 result['command'] = result.multilineCommand or result.command | |
547 result['raw'] = raw | |
548 result['clean'] = self.commentGrammars.transformString(result.args) | |
549 result['expanded'] = s | |
550 p = ParsedString(result.clean) | |
551 p.parsed = result | |
552 p.parser = self.parsed | |
553 for (key, val) in kwargs.items(): | |
554 p.parsed[key] = val | |
555 return p | |
556 | |
557 def postparsing_precmd(self, statement): | |
558 stop = 0 | |
559 return stop, statement | |
247
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
560 |
230 | 561 def postparsing_postcmd(self, stop): |
562 return stop | |
247
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
563 def func_named(self, arg): |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
564 result = None |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
565 target = 'do_' + arg |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
566 if target in dir(self): |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
567 result = target |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
568 else: |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
569 if self.abbrev: # accept shortened versions of commands |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
570 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
|
571 if len(funcs) == 1: |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
572 result = 'do_' + funcs[0] |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
573 return result |
230 | 574 def onecmd(self, line): |
575 """Interpret the argument as though it had been typed in response | |
576 to the prompt. | |
577 | |
578 This may be overridden, but should not normally need to be; | |
579 see the precmd() and postcmd() methods for useful execution hooks. | |
580 The return value is a flag indicating whether interpretation of | |
581 commands by the interpreter should stop. | |
582 | |
583 This (`cmd2`) version of `onecmd` already override's `cmd`'s `onecmd`. | |
584 | |
585 """ | |
586 if not line: | |
587 return self.emptyline() | |
588 if not pyparsing.Or(self.commentGrammars).setParseAction(lambda x: '').transformString(line): | |
589 return 0 # command was empty except for comments | |
590 try: | |
591 statement = self.parsed(line) | |
592 while statement.parsed.multilineCommand and (statement.parsed.terminator == ''): | |
593 statement = '%s\n%s' % (statement.parsed.raw, | |
594 self.pseudo_raw_input(self.continuation_prompt)) | |
595 statement = self.parsed(statement) | |
596 except Exception, e: | |
597 print e | |
598 return 0 | |
246 | 599 if statement.parsed.command not in self.excludeFromHistory: |
600 self.history.append(statement.parsed.raw) | |
230 | 601 try: |
602 (stop, statement) = self.postparsing_precmd(statement) | |
603 except Exception, e: | |
604 print str(e) | |
605 return 0 | |
606 if stop: | |
607 return self.postparsing_postcmd(stop) | |
608 | |
609 if not statement.parsed.command: | |
610 return self.postparsing_postcmd(stop=0) | |
611 | |
612 statekeeper = None | |
613 | |
614 if statement.parsed.pipeTo: | |
615 redirect = subprocess.Popen(statement.parsed.pipeTo, shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
616 statekeeper = Statekeeper(self, ('stdout',)) | |
617 self.stdout = redirect.stdin | |
618 elif statement.parsed.output: | |
619 statekeeper = Statekeeper(self, ('stdout',)) | |
620 if statement.parsed.outputTo: | |
621 mode = 'w' | |
622 if statement.parsed.output == '>>': | |
623 mode = 'a' | |
624 try: | |
625 self.stdout = open(os.path.expanduser(statement.parsed.outputTo), mode) | |
626 except OSError, e: | |
627 print e | |
628 return self.postparsing_postcmd(stop=0) | |
629 else: | |
630 statekeeper = Statekeeper(self, ('stdout',)) | |
631 self.stdout = tempfile.TemporaryFile() | |
632 if statement.parsed.output == '>>': | |
633 self.stdout.write(getPasteBuffer()) | |
634 try: | |
635 # "heart" of the command, replace's cmd's onecmd() | |
636 self.lastcmd = statement.parsed.expanded | |
247
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
637 funcname = self.func_named(statement.parsed.command) |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
638 if not funcname: |
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
639 return self.postparsing_postcmd(self.default(statement)) |
230 | 640 timestart = datetime.datetime.now() |
247
3db4166a54ce
abbrevs working with help
catherine@Elli.myhome.westell.com
parents:
246
diff
changeset
|
641 stop = getattr(self, funcname)(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 = '' | |
1113 def setUp(self): | |
1114 if self.CmdApp: | |
1115 self.outputTrap = OutputTrap() | |
1116 self.cmdapp = self.CmdApp() | |
1117 try: | |
1118 tfile = open(os.path.expanduser(self.transcriptFileName)) | |
1119 self.transcript = iter(tfile.readlines()) | |
1120 tfile.close() | |
1121 except IOError: | |
1122 self.transcript = [] | |
1123 def assertEqualEnough(self, got, expected, message): | |
1124 got = got.strip().splitlines() | |
1125 expected = expected.strip().splitlines() | |
1126 self.assertEqual(len(got), len(expected), message) | |
1127 for (linegot, lineexpected) in zip(got, expected): | |
1128 matchme = re.escape(lineexpected.strip()).replace('\\*', '.*'). \ | |
1129 replace('\\ ', ' ') | |
1130 self.assert_(re.match(matchme, linegot.strip()), message) | |
1131 def testall(self): | |
1132 if self.CmdApp: | |
1133 lineNum = 0 | |
1134 try: | |
1135 line = self.transcript.next() | |
1136 while True: | |
1137 while not line.startswith(self.cmdapp.prompt): | |
1138 line = self.transcript.next() | |
1139 command = [line[len(self.cmdapp.prompt):]] | |
1140 line = self.transcript.next() | |
1141 while line.startswith(self.cmdapp.continuation_prompt): | |
1142 command.append(line[len(self.cmdapp.continuation_prompt):]) | |
1143 line = self.transcript.next() | |
1144 command = ''.join(command) | |
1145 self.cmdapp.onecmd(command) | |
1146 result = self.outputTrap.read() | |
1147 if line.startswith(self.cmdapp.prompt): | |
1148 self.assertEqualEnough(result.strip(), '', | |
1149 '\nFile %s, line %d\nCommand was:\n%s\nExpected: (nothing) \nGot:\n%s\n' % | |
1150 (self.transcriptFileName, lineNum, command, result)) | |
1151 continue | |
1152 expected = [] | |
1153 while not line.startswith(self.cmdapp.prompt): | |
1154 expected.append(line) | |
1155 line = self.transcript.next() | |
1156 expected = ''.join(expected) | |
1157 self.assertEqualEnough(expected.strip(), result.strip(), | |
1158 '\nFile %s, line %d\nCommand was:\n%s\nExpected:\n%s\nGot:\n%s\n' % | |
1159 (self.transcriptFileName, lineNum, command, expected, result)) | |
1160 # this needs to account for a line-by-line strip()ping | |
1161 except StopIteration: | |
1162 pass | |
1163 # catch the final output? | |
1164 def tearDown(self): | |
1165 if self.CmdApp: | |
1166 self.outputTrap.tearDown() | |
1167 | |
1168 if __name__ == '__main__': | |
1169 doctest.testmod(optionflags = doctest.NORMALIZE_WHITESPACE) | |
1170 #c = Cmd() |