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