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