diff cmd2.py @ 309:1941e54cb776

added bash-style SELECT
author catherine@dellzilla
date Fri, 29 Jan 2010 10:32:40 -0500
parents 4e9011c3f732
children 9d91406ca3a7
line wrap: on
line diff
--- a/cmd2.py	Thu Jan 28 08:52:04 2010 -0500
+++ b/cmd2.py	Fri Jan 29 10:32:40 2010 -0500
@@ -38,7 +38,11 @@
 from code import InteractiveConsole, InteractiveInterpreter, softspace
 from optparse import make_option
 
-import pyparsing
+if sys.version_info[0] > 2:
+    import pyparsing_py3 as pyparsing
+else:
+    import pyparsing
+    
 __version__ = '0.5.6'
 
 class OptionParser(optparse.OptionParser):
@@ -830,6 +834,23 @@
     do_exit = do_quit
     do_q = do_quit
     
+    def select(self, options, prompt='Your choice? '):
+        '''Presents a numbered menu to the user.  Modelled after
+           the bash shell's SELECT.  Returns the item chosen.'''
+        if isinstance(options, basestring):
+            options = options.split()
+        for (idx, opt) in enumerate(options):
+            self.poutput('  %2d. %s\n' % (idx+1, opt))
+        while True:
+            response = raw_input(prompt)
+            try:
+                response = int(response)
+                result = options[response - 1]
+                break
+            except ValueError:
+                pass # loop and ask again
+        return result
+    
     @options([make_option('-l', '--long', action="store_true",
                  help="describe function of parameter")])    
     def do_show(self, arg, opts):