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