comparison cmd2.py @ 247:3db4166a54ce

abbrevs working with help
author catherine@Elli.myhome.westell.com
date Mon, 30 Mar 2009 08:27:35 -0400
parents 2e37155d2b95
children 575652efb3d8
comparison
equal deleted inserted replaced
246:2e37155d2b95 247:3db4166a54ce
24 CHANGES: 24 CHANGES:
25 As of 0.3.0, options should be specified as `optparse` options. See README.txt. 25 As of 0.3.0, options should be specified as `optparse` options. See README.txt.
26 flagReader.py options are still supported for backward compatibility 26 flagReader.py options are still supported for backward compatibility
27 """ 27 """
28 import cmd, re, os, sys, optparse, subprocess, tempfile, pyparsing, doctest 28 import cmd, re, os, sys, optparse, subprocess, tempfile, pyparsing, doctest
29 import unittest, string, datetime, urllib, inspect, itertools 29 import unittest, string, datetime, urllib
30 from code import InteractiveConsole, InteractiveInterpreter, softspace 30 from code import InteractiveConsole, InteractiveInterpreter, softspace
31 from optparse import make_option 31 from optparse import make_option
32 __version__ = '0.5.0' 32 __version__ = '0.5.0'
33 33
34 class OptionParser(optparse.OptionParser): 34 class OptionParser(optparse.OptionParser):
290 'terminators': str(self.terminators), 290 'terminators': str(self.terminators),
291 'settable': ' '.join(self.settable) 291 'settable': ' '.join(self.settable)
292 }) 292 })
293 293
294 def do_help(self, arg): 294 def do_help(self, arg):
295 try: 295 funcname = self.func_named(arg)
296 fn = getattr(self, 'do_' + arg) 296 if funcname:
297 if fn and fn.optionParser: 297 fn = getattr(self, funcname)
298 try:
298 fn.optionParser.print_help(file=self.stdout) 299 fn.optionParser.print_help(file=self.stdout)
299 return 300 except AttributeError:
300 except AttributeError: 301 cmd.Cmd.do_help(self, funcname[3:])
301 pass
302 cmd.Cmd.do_help(self, arg)
303 302
304 def __init__(self, *args, **kwargs): 303 def __init__(self, *args, **kwargs):
305 cmd.Cmd.__init__(self, *args, **kwargs) 304 cmd.Cmd.__init__(self, *args, **kwargs)
306 self.history = History() 305 self.history = History()
307 self._init_parser() 306 self._init_parser()
308 self.pystate = {} 307 self.pystate = {}
309 self.shortcuts = sorted(self.shortcuts.items(), reverse=True) 308 self.shortcuts = sorted(self.shortcuts.items(), reverse=True)
310 self.keywords = list(itertools.izip(self.reserved_words, itertools.repeat(None))) + \ 309 self.keywords = self.reserved_words + [fname[3:] for fname in dir(self)
311 [(fname[3:], func) for (fname, func) in 310 if fname.startswith('do_')]
312 inspect.getmembers(self, inspect.ismethod)
313 if fname.startswith('do_')]
314
315 def do_shortcuts(self, args): 311 def do_shortcuts(self, args):
316 """Lists single-key shortcuts available.""" 312 """Lists single-key shortcuts available."""
317 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts)) 313 result = "\n".join('%s: %s' % (sc[0], sc[1]) for sc in sorted(self.shortcuts))
318 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result)) 314 self.stdout.write("Single-key shortcuts for other commands:\n%s\n" % (result))
319 315
559 return p 555 return p
560 556
561 def postparsing_precmd(self, statement): 557 def postparsing_precmd(self, statement):
562 stop = 0 558 stop = 0
563 return stop, statement 559 return stop, statement
560
564 def postparsing_postcmd(self, stop): 561 def postparsing_postcmd(self, stop):
565 return stop 562 return stop
563 def func_named(self, arg):
564 result = None
565 target = 'do_' + arg
566 if target in dir(self):
567 result = target
568 else:
569 if self.abbrev: # accept shortened versions of commands
570 funcs = [fname for fname in self.keywords if fname.startswith(arg)]
571 if len(funcs) == 1:
572 result = 'do_' + funcs[0]
573 return result
566 def onecmd(self, line): 574 def onecmd(self, line):
567 """Interpret the argument as though it had been typed in response 575 """Interpret the argument as though it had been typed in response
568 to the prompt. 576 to the prompt.
569 577
570 This may be overridden, but should not normally need to be; 578 This may be overridden, but should not normally need to be;
624 if statement.parsed.output == '>>': 632 if statement.parsed.output == '>>':
625 self.stdout.write(getPasteBuffer()) 633 self.stdout.write(getPasteBuffer())
626 try: 634 try:
627 # "heart" of the command, replace's cmd's onecmd() 635 # "heart" of the command, replace's cmd's onecmd()
628 self.lastcmd = statement.parsed.expanded 636 self.lastcmd = statement.parsed.expanded
629 try: 637 funcname = self.func_named(statement.parsed.command)
630 func = getattr(self, 'do_' + statement.parsed.command) 638 if not funcname:
631 except AttributeError: 639 return self.postparsing_postcmd(self.default(statement))
632 func = None
633 if self.abbrev: # accept shortened versions of commands
634 funcs = [(fname, function) for (fname, function) in self.keywords
635 if fname.startswith(statement.parsed.command)]
636 if len(funcs) == 1:
637 func = funcs[0][1]
638 if not func:
639 return self.postparsing_postcmd(self.default(statement))
640 timestart = datetime.datetime.now() 640 timestart = datetime.datetime.now()
641 stop = func(statement) 641 stop = getattr(self, funcname)(statement)
642 if self.timing: 642 if self.timing:
643 print 'Elapsed: %s' % str(datetime.datetime.now() - timestart) 643 print 'Elapsed: %s' % str(datetime.datetime.now() - timestart)
644 except Exception, e: 644 except Exception, e:
645 print e 645 print e
646 finally: 646 finally: