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