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