Mercurial > python-cmd2
annotate cmd2.py @ 310:9d91406ca3a7
select polished
author | catherine@dellzilla |
---|---|
date | Fri, 29 Jan 2010 11:26:23 -0500 |
parents | 1941e54cb776 |
children | 54e2dd53ba38 |
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) | |
310 | 16 Bash-style ``select`` available |
230 | 17 |
18 Note that redirection with > and | will only work if `self.stdout.write()` | |
19 is used in place of `print`. The standard library's `cmd` module is | |
20 written to use `self.stdout.write()`, | |
21 | |
22 - Catherine Devlin, Jan 03 2008 - catherinedevlin.blogspot.com | |
23 | |
24 mercurial repository at http://www.assembla.com/wiki/show/python-cmd2 | |
25 """ | |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
26 import cmd |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
27 import re |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
28 import os |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
29 import sys |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
30 import optparse |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
31 import subprocess |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
32 import tempfile |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
33 import doctest |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
34 import unittest |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
35 import datetime |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
36 import urllib |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
37 import glob |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
38 import traceback |
235
78ad20c2eed0
py working better now; still needs a iscomplete=True on onecmd
catherine@dellzilla
parents:
234
diff
changeset
|
39 from code import InteractiveConsole, InteractiveInterpreter, softspace |
230 | 40 from optparse import make_option |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
41 |
309 | 42 if sys.version_info[0] > 2: |
43 import pyparsing_py3 as pyparsing | |
44 else: | |
45 import pyparsing | |
46 | |
280 | 47 __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
|
48 |
230 | 49 class OptionParser(optparse.OptionParser): |
50 def exit(self, status=0, msg=None): | |
51 self.values._exit = True | |
52 if msg: | |
53 print msg | |
54 | |
55 def print_help(self, *args, **kwargs): | |
56 try: | |
57 print self._func.__doc__ | |
58 except AttributeError: | |
59 pass | |
60 optparse.OptionParser.print_help(self, *args, **kwargs) | |
61 | |
62 def error(self, msg): | |
63 """error(msg : string) | |
64 | |
65 Print a usage message incorporating 'msg' to stderr and exit. | |
66 If you override this in a subclass, it should not return -- it | |
67 should either exit or raise an exception. | |
68 """ | |
69 raise | |
70 | |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
71 def remaining_args(oldArgs, newArgList): |
230 | 72 ''' |
285 | 73 Preserves the spacing originally in the argument after |
74 the removal of options. | |
75 | |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
76 >>> remaining_args('-f bar bar cow', ['bar', 'cow']) |
230 | 77 'bar cow' |
78 ''' | |
79 pattern = '\s+'.join(re.escape(a) for a in newArgList) + '\s*$' | |
80 matchObj = re.search(pattern, oldArgs) | |
81 return oldArgs[matchObj.start():] | |
280 | 82 |
83 def _attr_get_(obj, attr): | |
84 '''Returns an attribute's value, or None (no error) if undefined. | |
286 | 85 Analagous to .get() for dictionaries. Useful when checking for |
86 value of options that may not have been defined on a given | |
87 method.''' | |
280 | 88 try: |
89 return getattr(obj, attr) | |
90 except AttributeError: | |
91 return None | |
283 | 92 |
93 optparse.Values.get = _attr_get_ | |
94 | |
230 | 95 def options(option_list): |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
96 '''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
|
97 alters a cmd2 methodo populate its ``opts`` argument from its |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
98 raw text argument. |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
99 |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
100 Example: transform |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
101 def do_something(self, arg): |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
102 |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
103 into |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
104 @options([make_option('-q', '--quick', action="store_true", |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
105 help="Makes things fast")]) |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
106 def do_something(self, arg, opts): |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
107 if opts.quick: |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
108 self.fast_button = True |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
109 ''' |
296 | 110 if not isinstance(option_list, list): |
298 | 111 option_list = [option_list] |
230 | 112 def option_setup(func): |
113 optionParser = OptionParser() | |
114 for opt in option_list: | |
115 optionParser.add_option(opt) | |
116 optionParser.set_usage("%s [options] arg" % func.__name__.strip('do_')) | |
117 optionParser._func = func | |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
118 def new_func(instance, arg): |
230 | 119 try: |
302 | 120 opts, newArgList = optionParser.parse_args(arg.split()) |
285 | 121 # Must find the remaining args in the original argument list, but |
122 # mustn't include the command itself | |
302 | 123 #if hasattr(arg, 'parsed') and newArgList[0] == arg.parsed.command: |
124 # newArgList = newArgList[1:] | |
125 newArgs = remaining_args(arg, newArgList) | |
301 | 126 if isinstance(arg, ParsedString): |
127 arg = arg.with_args_replaced(newArgs) | |
128 else: | |
129 arg = newArgs | |
230 | 130 except (optparse.OptionValueError, optparse.BadOptionError, |
131 optparse.OptionError, optparse.AmbiguousOptionError, | |
132 optparse.OptionConflictError), e: | |
133 print e | |
134 optionParser.print_help() | |
135 return | |
136 if hasattr(opts, '_exit'): | |
137 return None | |
138 result = func(instance, arg, opts) | |
139 return result | |
289 | 140 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
|
141 return new_func |
230 | 142 return option_setup |
143 | |
144 class PasteBufferError(EnvironmentError): | |
145 if sys.platform[:3] == 'win': | |
146 errmsg = """Redirecting to or from paste buffer requires pywin32 | |
147 to be installed on operating system. | |
148 Download from http://sourceforge.net/projects/pywin32/""" | |
149 else: | |
150 errmsg = """Redirecting to or from paste buffer requires xclip | |
151 to be installed on operating system. | |
152 On Debian/Ubuntu, 'sudo apt-get install xclip' will install it.""" | |
153 def __init__(self): | |
154 Exception.__init__(self, self.errmsg) | |
155 | |
156 pastebufferr = """Redirecting to or from paste buffer requires %s | |
157 to be installed on operating system. | |
158 %s""" | |
286 | 159 |
230 | 160 if subprocess.mswindows: |
161 try: | |
162 import win32clipboard | |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
163 def get_paste_buffer(): |
230 | 164 win32clipboard.OpenClipboard(0) |
165 try: | |
166 result = win32clipboard.GetClipboardData() | |
167 except TypeError: | |
168 result = '' #non-text | |
169 win32clipboard.CloseClipboard() | |
170 return result | |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
171 def write_to_paste_buffer(txt): |
230 | 172 win32clipboard.OpenClipboard(0) |
173 win32clipboard.EmptyClipboard() | |
174 win32clipboard.SetClipboardText(txt) | |
175 win32clipboard.CloseClipboard() | |
176 except ImportError: | |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
177 def get_paste_buffer(*args): |
230 | 178 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
|
179 setPasteBuffer = get_paste_buffer |
230 | 180 else: |
181 can_clip = False | |
182 try: | |
183 subprocess.check_call('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
184 can_clip = True | |
185 except AttributeError: # check_call not defined, Python < 2.5 | |
186 teststring = 'Testing for presence of xclip.' | |
187 xclipproc = subprocess.Popen('xclip -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
188 xclipproc.stdin.write(teststring) | |
189 xclipproc.stdin.close() | |
190 xclipproc = subprocess.Popen('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
191 if xclipproc.stdout.read() == teststring: | |
192 can_clip = True | |
193 except (subprocess.CalledProcessError, OSError, IOError): | |
194 pass | |
195 if can_clip: | |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
196 def get_paste_buffer(): |
230 | 197 xclipproc = subprocess.Popen('xclip -o -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) |
198 return xclipproc.stdout.read() | |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
199 def write_to_paste_buffer(txt): |
230 | 200 xclipproc = subprocess.Popen('xclip -sel clip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) |
201 xclipproc.stdin.write(txt) | |
202 xclipproc.stdin.close() | |
203 # but we want it in both the "primary" and "mouse" clipboards | |
204 xclipproc = subprocess.Popen('xclip', shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE) | |
205 xclipproc.stdin.write(txt) | |
206 xclipproc.stdin.close() | |
207 else: | |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
208 def get_paste_buffer(*args): |
230 | 209 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
|
210 setPasteBuffer = get_paste_buffer |
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
211 writeToPasteBuffer = get_paste_buffer |
230 | 212 |
213 pyparsing.ParserElement.setDefaultWhitespaceChars(' \t') | |
214 | |
215 class ParsedString(str): | |
300
1e4773b325d1
assume newfunc does not have to accept unparsed arguments
catherine@dellzilla
parents:
299
diff
changeset
|
216 def full_parsed_statement(self): |
1e4773b325d1
assume newfunc does not have to accept unparsed arguments
catherine@dellzilla
parents:
299
diff
changeset
|
217 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
|
218 new.parsed = self.parsed |
1e4773b325d1
assume newfunc does not have to accept unparsed arguments
catherine@dellzilla
parents:
299
diff
changeset
|
219 new.parser = self.parser |
301 | 220 return new |
221 def with_args_replaced(self, newargs): | |
222 new = ParsedString(newargs) | |
223 new.parsed = self.parsed | |
224 new.parser = self.parser | |
225 new.parsed['args'] = newargs | |
226 new.parsed.statement['args'] = newargs | |
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 | |
309 | 838 def select(self, options, prompt='Your choice? '): |
839 '''Presents a numbered menu to the user. Modelled after | |
310 | 840 the bash shell's SELECT. Returns the item chosen. |
841 | |
842 Argument ``options`` can be: | |
843 a single string -> will be split into one-word options | |
844 a list of strings -> will be offered as options | |
845 a list of tuples -> interpreted as (value, text), so | |
846 that the return value can differ from | |
847 the text advertised to the user ''' | |
309 | 848 if isinstance(options, basestring): |
310 | 849 options = zip(options.split(), options.split()) |
850 fulloptions = [] | |
851 for opt in options: | |
852 if isinstance(opt, basestring): | |
853 fulloptions.append((opt, opt)) | |
854 else: | |
855 try: | |
856 fulloptions.append((opt[0], opt[1])) | |
857 except IndexError: | |
858 fulloptions.append((opt[0], opt[0])) | |
859 for (idx, (value, text)) in enumerate(fulloptions): | |
860 self.poutput(' %2d. %s\n' % (idx+1, text)) | |
309 | 861 while True: |
862 response = raw_input(prompt) | |
863 try: | |
864 response = int(response) | |
310 | 865 result = fulloptions[response - 1][0] |
309 | 866 break |
867 except ValueError: | |
868 pass # loop and ask again | |
869 return result | |
870 | |
290 | 871 @options([make_option('-l', '--long', action="store_true", |
872 help="describe function of parameter")]) | |
873 def do_show(self, arg, opts): | |
230 | 874 '''Shows value of a parameter.''' |
290 | 875 param = arg.strip().lower() |
876 result = {} | |
877 maxlen = 0 | |
878 for p in self.settable: | |
879 if (not param) or p.startswith(param): | |
880 result[p] = '%s: %s' % (p, str(getattr(self, p))) | |
881 maxlen = max(maxlen, len(result[p])) | |
882 if result: | |
883 for p in sorted(result): | |
884 if opts.long: | |
885 self.poutput('%s # %s' % (result[p].ljust(maxlen), self.settable[p])) | |
886 else: | |
887 self.poutput(result[p]) | |
230 | 888 else: |
290 | 889 self.perror("Parameter '%s' not supported (type 'show' for list of parameters)." % param) |
230 | 890 |
891 def do_set(self, arg): | |
290 | 892 ''' |
893 Sets a cmd2 parameter. Accepts abbreviated parameter names so long | |
894 as there is no ambiguity. Call without arguments for a list of | |
895 settable parameters with their values.''' | |
230 | 896 try: |
291 | 897 statement, paramName, val = arg.parsed.raw.split(None, 2) |
230 | 898 paramName = paramName.strip().lower() |
290 | 899 if paramName not in self.settable: |
291 | 900 hits = [p for p in self.settable if p.startswith(paramName)] |
290 | 901 if len(hits) == 1: |
902 paramName = hits[0] | |
903 else: | |
904 return self.do_show(paramName) | |
905 currentVal = getattr(self, paramName) | |
906 if (val[0] == val[-1]) and val[0] in ("'", '"'): | |
907 val = val[1:-1] | |
908 else: | |
909 val = cast(currentVal, val) | |
910 setattr(self, paramName, val) | |
911 self.stdout.write('%s - was: %s\nnow: %s\n' % (paramName, currentVal, val)) | |
912 if currentVal != val: | |
913 try: | |
914 onchange_hook = getattr(self, '_onchange_%s' % paramName) | |
915 onchange_hook(old=currentVal, new=val) | |
916 except AttributeError: | |
917 pass | |
230 | 918 except (ValueError, AttributeError, NotSettableError), e: |
919 self.do_show(arg) | |
920 | |
921 def do_pause(self, arg): | |
922 'Displays the specified text then waits for the user to press RETURN.' | |
923 raw_input(arg + '\n') | |
924 | |
925 def do_shell(self, arg): | |
926 'execute a command as if at the OS prompt.' | |
927 os.system(arg) | |
267
3333e61e7103
poutput, perror, pfeedback
Catherine Devlin <catherine.devlin@gmail.com>
parents:
265
diff
changeset
|
928 |
233 | 929 def do_py(self, arg): |
230 | 930 ''' |
931 py <command>: Executes a Python command. | |
242 | 932 py: Enters interactive Python mode. |
933 End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, 'exit()`. | |
241 | 934 Non-python commands can be issued with `cmd("your command")`. |
230 | 935 ''' |
280 | 936 self.pystate['self'] = self |
274 | 937 arg = arg.parsed.raw[2:].strip() |
230 | 938 if arg.strip(): |
235
78ad20c2eed0
py working better now; still needs a iscomplete=True on onecmd
catherine@dellzilla
parents:
234
diff
changeset
|
939 interp = InteractiveInterpreter(locals=self.pystate) |
233 | 940 interp.runcode(arg) |
230 | 941 else: |
235
78ad20c2eed0
py working better now; still needs a iscomplete=True on onecmd
catherine@dellzilla
parents:
234
diff
changeset
|
942 interp = MyInteractiveConsole(locals=self.pystate) |
233 | 943 def quit(): |
234 | 944 raise EmbeddedConsoleExit |
236 | 945 def onecmd(arg): |
946 return self.onecmd(arg + '\n') | |
233 | 947 self.pystate['quit'] = quit |
948 self.pystate['exit'] = quit | |
234 | 949 try: |
240 | 950 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
|
951 keepstate = Statekeeper(sys, ('stdin','stdout')) |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
952 sys.stdout = self.stdout |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
953 sys.stdin = self.stdin |
240 | 954 interp.interact(banner= "Python %s on %s\n%s\n(%s)\n%s" % |
955 (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
|
956 except EmbeddedConsoleExit: |
245 | 957 pass |
958 keepstate.restore() | |
233 | 959 |
230 | 960 def do_history(self, arg): |
961 """history [arg]: lists past commands issued | |
962 | |
963 no arg -> list all | |
964 arg is integer -> list one history item, by index | |
965 arg is string -> string search | |
966 arg is /enclosed in forward-slashes/ -> regular expression search | |
967 """ | |
968 if arg: | |
969 history = self.history.get(arg) | |
970 else: | |
971 history = self.history | |
972 for hi in history: | |
973 self.stdout.write(hi.pr()) | |
974 def last_matching(self, arg): | |
975 try: | |
976 if arg: | |
977 return self.history.get(arg)[-1] | |
978 else: | |
979 return self.history[-1] | |
980 except IndexError: | |
981 return None | |
982 def do_list(self, arg): | |
983 """list [arg]: lists last command issued | |
984 | |
307 | 985 no arg -> list most recent command |
230 | 986 arg is integer -> list one history item, by index |
307 | 987 a..b, a:b, a:, ..b -> list spans from a (or start) to b (or end) |
308 | 988 arg is string -> list all commands matching string search |
230 | 989 arg is /enclosed in forward-slashes/ -> regular expression search |
990 """ | |
991 try: | |
308 | 992 history = self.history.span(arg or '-1') |
993 except IndexError: | |
994 history = self.history.search(arg) | |
995 for hi in history: | |
996 self.poutput(hi.pr()) | |
997 | |
230 | 998 do_hi = do_history |
999 do_l = do_list | |
1000 do_li = do_list | |
1001 | |
1002 def do_ed(self, arg): | |
1003 """ed: edit most recent command in text editor | |
1004 ed [N]: edit numbered command from history | |
1005 ed [filename]: edit specified file name | |
1006 | |
1007 commands are run after editor is closed. | |
1008 "set edit (program-name)" or set EDITOR environment variable | |
1009 to control which editing program is used.""" | |
1010 if not self.editor: | |
267
3333e61e7103
poutput, perror, pfeedback
Catherine Devlin <catherine.devlin@gmail.com>
parents:
265
diff
changeset
|
1011 self.perror("Please use 'set editor' to specify your text editing program of choice.") |
230 | 1012 return |
1013 filename = self.default_file_name | |
1014 if arg: | |
1015 try: | |
1016 buffer = self.last_matching(int(arg)) | |
1017 except ValueError: | |
1018 filename = arg | |
1019 buffer = '' | |
1020 else: | |
1021 buffer = self.history[-1] | |
1022 | |
1023 if buffer: | |
1024 f = open(os.path.expanduser(filename), 'w') | |
1025 f.write(buffer or '') | |
1026 f.close() | |
1027 | |
1028 os.system('%s %s' % (self.editor, filename)) | |
1029 self.do__load(filename) | |
1030 do_edit = do_ed | |
1031 | |
1032 saveparser = (pyparsing.Optional(pyparsing.Word(pyparsing.nums)^'*')("idx") + | |
1033 pyparsing.Optional(pyparsing.Word(legalChars + '/\\'))("fname") + | |
1034 pyparsing.stringEnd) | |
1035 def do_save(self, arg): | |
1036 """`save [N] [filename.ext]` | |
1037 Saves command from history to file. | |
1038 N => Number of command (from history), or `*`; | |
1039 most recent command if omitted""" | |
1040 | |
1041 try: | |
1042 args = self.saveparser.parseString(arg) | |
1043 except pyparsing.ParseException: | |
267
3333e61e7103
poutput, perror, pfeedback
Catherine Devlin <catherine.devlin@gmail.com>
parents:
265
diff
changeset
|
1044 self.perror(self.do_save.__doc__) |
230 | 1045 return |
1046 fname = args.fname or self.default_file_name | |
1047 if args.idx == '*': | |
1048 saveme = '\n\n'.join(self.history[:]) | |
1049 elif args.idx: | |
1050 saveme = self.history[int(args.idx)-1] | |
1051 else: | |
1052 saveme = self.history[-1] | |
1053 try: | |
1054 f = open(os.path.expanduser(fname), 'w') | |
1055 f.write(saveme) | |
1056 f.close() | |
267
3333e61e7103
poutput, perror, pfeedback
Catherine Devlin <catherine.devlin@gmail.com>
parents:
265
diff
changeset
|
1057 self.pfeedback('Saved to %s' % (fname)) |
230 | 1058 except Exception, e: |
267
3333e61e7103
poutput, perror, pfeedback
Catherine Devlin <catherine.devlin@gmail.com>
parents:
265
diff
changeset
|
1059 self.perror('Error saving %s: %s' % (fname, str(e))) |
230 | 1060 |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1061 def read_file_or_url(self, fname): |
288
e743cf74c518
hooray, fixed bad comment parser - all unit tests pass
catherine@bothari
parents:
287
diff
changeset
|
1062 # TODO: not working on localhost |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1063 if isinstance(fname, file): |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
1064 result = open(fname, 'r') |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1065 else: |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1066 match = self.urlre.match(fname) |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1067 if match: |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
1068 result = urllib.urlopen(match.group(1)) |
230 | 1069 else: |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1070 fname = os.path.expanduser(fname) |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1071 try: |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1072 result = open(os.path.expanduser(fname), 'r') |
287
1cd23003e8d5
refactoring, but something went wrong with comments
catherine@bothari
parents:
286
diff
changeset
|
1073 except IOError: |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1074 result = open('%s.%s' % (os.path.expanduser(fname), |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1075 self.defaultExtension), 'r') |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1076 return result |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1077 |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1078 def do__relative_load(self, arg=None): |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1079 ''' |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1080 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
|
1081 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
|
1082 already-running script's directory.''' |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1083 if arg: |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1084 arg = arg.split(None, 1) |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1085 targetname, args = arg[0], (arg[1:] or [''])[0] |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1086 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
|
1087 self.do__load('%s %s' % (targetname, args)) |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1088 |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1089 urlre = re.compile('(https?://[-\\w\\./]+)') |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1090 def do_load(self, arg=None): |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1091 """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
|
1092 if arg is None: |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1093 targetname = self.default_file_name |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1094 else: |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1095 arg = arg.split(None, 1) |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1096 targetname, args = arg[0], (arg[1:] or [''])[0].strip() |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1097 try: |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1098 target = self.read_file_or_url(targetname) |
230 | 1099 except IOError, e: |
267
3333e61e7103
poutput, perror, pfeedback
Catherine Devlin <catherine.devlin@gmail.com>
parents:
265
diff
changeset
|
1100 self.perror('Problem accessing script from %s: \n%s' % (targetname, e)) |
230 | 1101 return |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1102 keepstate = Statekeeper(self, ('stdin','use_rawinput','prompt', |
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1103 'continuation_prompt','current_script_dir')) |
230 | 1104 self.stdin = target |
1105 self.use_rawinput = False | |
1106 self.prompt = self.continuation_prompt = '' | |
244
e0c60ea7ad5d
midway through py script change
catherine@Elli.myhome.westell.com
parents:
243
diff
changeset
|
1107 self.current_script_dir = os.path.split(targetname)[0] |
230 | 1108 stop = self.cmdloop() |
1109 self.stdin.close() | |
1110 keepstate.restore() | |
1111 self.lastcmd = '' | |
1112 return (stop == self._STOP_AND_EXIT) and self._STOP_AND_EXIT | |
1113 do__load = do_load # avoid an unfortunate legacy use of do_load from sqlpython | |
1114 | |
1115 def do_run(self, arg): | |
1116 """run [arg]: re-runs an earlier command | |
1117 | |
1118 no arg -> run most recent command | |
1119 arg is integer -> run one history item, by index | |
1120 arg is string -> run most recent command by string search | |
1121 arg is /enclosed in forward-slashes/ -> run most recent by regex | |
1122 """ | |
1123 'run [N]: runs the SQL that was run N commands ago' | |
1124 runme = self.last_matching(arg) | |
267
3333e61e7103
poutput, perror, pfeedback
Catherine Devlin <catherine.devlin@gmail.com>
parents:
265
diff
changeset
|
1125 self.pfeedback(runme) |
230 | 1126 if runme: |
1127 runme = self.precmd(runme) | |
1128 stop = self.onecmd(runme) | |
1129 stop = self.postcmd(stop, runme) | |
1130 do_r = do_run | |
1131 | |
1132 def fileimport(self, statement, source): | |
1133 try: | |
1134 f = open(os.path.expanduser(source)) | |
1135 except IOError: | |
1136 self.stdout.write("Couldn't read from file %s\n" % source) | |
1137 return '' | |
1138 data = f.read() | |
1139 f.close() | |
1140 return data | |
1141 | |
1142 class HistoryItem(str): | |
305 | 1143 listformat = '-------------------------[%d]\n%s\n' |
230 | 1144 def __init__(self, instr): |
1145 str.__init__(self) | |
1146 self.lowercase = self.lower() | |
1147 self.idx = None | |
1148 def pr(self): | |
307 | 1149 return self.listformat % (self.idx, str(self)) |
230 | 1150 |
1151 class History(list): | |
305 | 1152 '''A list of HistoryItems that knows how to respond to user requests. |
1153 >>> h = History([HistoryItem('first'), HistoryItem('second'), HistoryItem('third'), HistoryItem('fourth')]) | |
1154 >>> h.span('-2..') | |
1155 ['third', 'fourth'] | |
1156 >>> h.span('2..3') | |
1157 ['second', 'third'] | |
1158 >>> h.span('3') | |
1159 ['third'] | |
1160 >>> h.span(':') | |
1161 ['first', 'second', 'third', 'fourth'] | |
1162 >>> h.span('2..') | |
1163 ['second', 'third', 'fourth'] | |
1164 >>> h.span('-1') | |
1165 ['fourth'] | |
1166 >>> h.span('-2..-3') | |
306 | 1167 ['third', 'second'] |
308 | 1168 >>> h.search('o') |
1169 ['second', 'fourth'] | |
1170 >>> h.search('/IR/') | |
1171 ['first', 'third'] | |
305 | 1172 ''' |
1173 def zero_based_index(self, onebased): | |
1174 result = onebased | |
1175 if result > 0: | |
1176 result -= 1 | |
1177 return result | |
1178 def to_index(self, raw): | |
1179 if raw: | |
1180 result = self.zero_based_index(int(raw)) | |
1181 else: | |
1182 result = None | |
1183 return result | |
308 | 1184 def search(self, target): |
1185 target = target.strip() | |
1186 if target[0] == target[-1] == '/' and len(target) > 1: | |
1187 target = target[1:-1] | |
1188 else: | |
1189 target = re.escape(target) | |
1190 pattern = re.compile(target, re.IGNORECASE) | |
1191 return [s for s in self if pattern.search(s)] | |
305 | 1192 spanpattern = re.compile(r'^\s*(?P<start>\-?\d+)?\s*(?P<separator>:|(\.{2,}))?\s*(?P<end>\-?\d+)?\s*$') |
1193 def span(self, raw): | |
308 | 1194 if raw.lower() in ('*', '-', 'all'): |
1195 raw = ':' | |
305 | 1196 results = self.spanpattern.search(raw) |
307 | 1197 if not results: |
1198 raise IndexError | |
305 | 1199 if not results.group('separator'): |
1200 return [self[self.to_index(results.group('start'))]] | |
1201 start = self.to_index(results.group('start')) | |
1202 end = self.to_index(results.group('end')) | |
1203 reverse = False | |
1204 if end is not None: | |
1205 if end < start: | |
1206 (start, end) = (end, start) | |
1207 reverse = True | |
1208 end += 1 | |
1209 result = self[start:end] | |
1210 if reverse: | |
1211 result.reverse() | |
1212 return result | |
1213 | |
1214 rangePattern = re.compile(r'^\s*(?P<start>[\d]+)?\s*\-\s*(?P<end>[\d]+)?\s*$') | |
230 | 1215 def append(self, new): |
1216 new = HistoryItem(new) | |
1217 list.append(self, new) | |
1218 new.idx = len(self) | |
1219 def extend(self, new): | |
1220 for n in new: | |
1221 self.append(n) | |
305 | 1222 |
1223 | |
1224 def get(self, getme=None, fromEnd=False): | |
1225 if not getme: | |
1226 return self | |
230 | 1227 try: |
1228 getme = int(getme) | |
1229 if getme < 0: | |
1230 return self[:(-1 * getme)] | |
1231 else: | |
1232 return [self[getme-1]] | |
1233 except IndexError: | |
1234 return [] | |
305 | 1235 except ValueError: |
1236 rangeResult = self.rangePattern.search(getme) | |
1237 if rangeResult: | |
1238 start = rangeResult.group('start') or None | |
1239 end = rangeResult.group('start') or None | |
1240 if start: | |
1241 start = int(start) - 1 | |
1242 if end: | |
1243 end = int(end) | |
1244 return self[start:end] | |
1245 | |
230 | 1246 getme = getme.strip() |
305 | 1247 |
230 | 1248 if getme.startswith(r'/') and getme.endswith(r'/'): |
1249 finder = re.compile(getme[1:-1], re.DOTALL | re.MULTILINE | re.IGNORECASE) | |
1250 def isin(hi): | |
1251 return finder.search(hi) | |
1252 else: | |
1253 def isin(hi): | |
1254 return (getme.lower() in hi.lowercase) | |
1255 return [itm for itm in self if isin(itm)] | |
1256 | |
1257 class NotSettableError(Exception): | |
1258 pass | |
1259 | |
1260 def cast(current, new): | |
1261 """Tries to force a new value into the same type as the current.""" | |
1262 typ = type(current) | |
1263 if typ == bool: | |
1264 try: | |
1265 return bool(int(new)) | |
1266 except ValueError, TypeError: | |
1267 pass | |
1268 try: | |
1269 new = new.lower() | |
1270 except: | |
1271 pass | |
1272 if (new=='on') or (new[0] in ('y','t')): | |
1273 return True | |
1274 if (new=='off') or (new[0] in ('n','f')): | |
1275 return False | |
1276 else: | |
1277 try: | |
1278 return typ(new) | |
1279 except: | |
1280 pass | |
1281 print "Problem setting parameter (now %s) to %s; incorrect type?" % (current, new) | |
1282 return current | |
1283 | |
1284 class Statekeeper(object): | |
1285 def __init__(self, obj, attribs): | |
1286 self.obj = obj | |
1287 self.attribs = attribs | |
282 | 1288 if self.obj: |
1289 self.save() | |
230 | 1290 def save(self): |
1291 for attrib in self.attribs: | |
1292 setattr(self, attrib, getattr(self.obj, attrib)) | |
1293 def restore(self): | |
282 | 1294 if self.obj: |
1295 for attrib in self.attribs: | |
1296 setattr(self.obj, attrib, getattr(self, attrib)) | |
230 | 1297 |
1298 class Borg(object): | |
1299 '''All instances of any Borg subclass will share state. | |
1300 from Python Cookbook, 2nd Ed., recipe 6.16''' | |
1301 _shared_state = {} | |
1302 def __new__(cls, *a, **k): | |
1303 obj = object.__new__(cls, *a, **k) | |
1304 obj.__dict__ = cls._shared_state | |
1305 return obj | |
1306 | |
1307 class OutputTrap(Borg): | |
1308 '''Instantiate an OutputTrap to divert/capture ALL stdout output. For use in unit testing. | |
1309 Call `tearDown()` to return to normal output.''' | |
1310 def __init__(self): | |
1311 self.old_stdout = sys.stdout | |
1312 self.trap = tempfile.TemporaryFile() | |
1313 sys.stdout = self.trap | |
1314 def read(self): | |
1315 self.trap.seek(0) | |
1316 result = self.trap.read() | |
1317 self.trap.truncate(0) | |
1318 return result.strip('\x00') | |
1319 def tearDown(self): | |
1320 sys.stdout = self.old_stdout | |
1321 | |
261
57070e181cf7
line end-stripping working in transcript testing
Catherine Devlin <catherine.devlin@gmail.com>
parents:
260
diff
changeset
|
1322 |
230 | 1323 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
|
1324 '''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
|
1325 that will execute the commands in a transcript file and expect the results shown. |
230 | 1326 See example.py''' |
1327 CmdApp = None | |
253
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1328 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
|
1329 self.transcripts = {} |
259
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1330 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
|
1331 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
|
1332 tfile = open(fname) |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1333 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
|
1334 tfile.close() |
260
2b69c4d72cd8
unfinished experiments with testing for regular expressions
Catherine Devlin <catherine.devlin@gmail.com>
parents:
259
diff
changeset
|
1335 if not len(self.transcripts): |
2b69c4d72cd8
unfinished experiments with testing for regular expressions
Catherine Devlin <catherine.devlin@gmail.com>
parents:
259
diff
changeset
|
1336 raise StandardError, "No test files found - nothing to test." |
230 | 1337 def setUp(self): |
1338 if self.CmdApp: | |
1339 self.outputTrap = OutputTrap() | |
1340 self.cmdapp = self.CmdApp() | |
253
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1341 self.fetchTranscripts() |
230 | 1342 def testall(self): |
1343 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
|
1344 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
|
1345 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
|
1346 self._test_transcript(fname, transcript) |
261
57070e181cf7
line end-stripping working in transcript testing
Catherine Devlin <catherine.devlin@gmail.com>
parents:
260
diff
changeset
|
1347 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
|
1348 regexPattern.ignore(pyparsing.cStyleComment) |
57070e181cf7
line end-stripping working in transcript testing
Catherine Devlin <catherine.devlin@gmail.com>
parents:
260
diff
changeset
|
1349 notRegexPattern = pyparsing.Word(pyparsing.printables) |
57070e181cf7
line end-stripping working in transcript testing
Catherine Devlin <catherine.devlin@gmail.com>
parents:
260
diff
changeset
|
1350 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
|
1351 expectationParser = regexPattern | notRegexPattern |
57070e181cf7
line end-stripping working in transcript testing
Catherine Devlin <catherine.devlin@gmail.com>
parents:
260
diff
changeset
|
1352 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
|
1353 def _test_transcript(self, fname, transcript): |
253
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1354 lineNum = 0 |
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1355 try: |
304
8c96f829ba1b
tweaking transcript test newlines (complete)
catherine@dellzilla
parents:
303
diff
changeset
|
1356 line = transcript.next() |
253
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1357 while True: |
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1358 while not line.startswith(self.cmdapp.prompt): |
304
8c96f829ba1b
tweaking transcript test newlines (complete)
catherine@dellzilla
parents:
303
diff
changeset
|
1359 line = transcript.next() |
253
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1360 command = [line[len(self.cmdapp.prompt):]] |
304
8c96f829ba1b
tweaking transcript test newlines (complete)
catherine@dellzilla
parents:
303
diff
changeset
|
1361 line = transcript.next() |
253
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1362 while line.startswith(self.cmdapp.continuation_prompt): |
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1363 command.append(line[len(self.cmdapp.continuation_prompt):]) |
304
8c96f829ba1b
tweaking transcript test newlines (complete)
catherine@dellzilla
parents:
303
diff
changeset
|
1364 line = transcript.next() |
305 | 1365 command = ''.join(command).strip() |
1366 self.cmdapp.onecmd(command) | |
260
2b69c4d72cd8
unfinished experiments with testing for regular expressions
Catherine Devlin <catherine.devlin@gmail.com>
parents:
259
diff
changeset
|
1367 result = self.outputTrap.read().strip() |
253
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1368 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
|
1369 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
|
1370 (fname, lineNum, command, result) |
e81378f82c7c
transcript tests with regex now work smoothly
Catherine Devlin <catherine.devlin@gmail.com>
parents:
261
diff
changeset
|
1371 self.assert_(not(result.strip()), message) |
253
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1372 continue |
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1373 expected = [] |
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1374 while not line.startswith(self.cmdapp.prompt): |
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1375 expected.append(line) |
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1376 line = transcript.next() |
260
2b69c4d72cd8
unfinished experiments with testing for regular expressions
Catherine Devlin <catherine.devlin@gmail.com>
parents:
259
diff
changeset
|
1377 expected = ''.join(expected).strip() |
2b69c4d72cd8
unfinished experiments with testing for regular expressions
Catherine Devlin <catherine.devlin@gmail.com>
parents:
259
diff
changeset
|
1378 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
|
1379 (fname, lineNum, command, expected, result) |
57070e181cf7
line end-stripping working in transcript testing
Catherine Devlin <catherine.devlin@gmail.com>
parents:
260
diff
changeset
|
1380 expected = self.expectationParser.transformString(expected) |
57070e181cf7
line end-stripping working in transcript testing
Catherine Devlin <catherine.devlin@gmail.com>
parents:
260
diff
changeset
|
1381 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
|
1382 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
|
1383 except StopIteration: |
24289178b367
midway through allowing multiple testing files
Catherine Devlin <catherine.devlin@gmail.com>
parents:
251
diff
changeset
|
1384 pass |
230 | 1385 def tearDown(self): |
1386 if self.CmdApp: | |
1387 self.outputTrap.tearDown() | |
1388 | |
1389 if __name__ == '__main__': | |
259
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1390 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
|
1391 |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1392 ''' |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1393 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
|
1394 (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
|
1395 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
|
1396 as a test for future |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1397 |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1398 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
|
1399 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
|
1400 |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1401 |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1402 class TestMyAppCase(Cmd2TestCase): |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1403 CmdApp = CmdLineApp |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1404 parser = optparse.OptionParser() |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1405 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
|
1406 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
|
1407 (callopts, callargs) = parser.parse_args() |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1408 if callopts.test: |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1409 CmdLineApp.testfiles = callargs |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1410 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
|
1411 unittest.main() |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1412 else: |
5147fa4166b0
multiple transcript tests working - sinister BASH trick defeated
Catherine Devlin <catherine.devlin@gmail.com>
parents:
258
diff
changeset
|
1413 CmdLineApp().cmdloop() |
286 | 1414 ''' |