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