# HG changeset patch # User catherine@dellzilla # Date 1264779160 18000 # Node ID 1941e54cb7764bd2ce996ee4ee7f24296296b0a9 # Parent 4e9011c3f732850246d0fdac500653fb2e453b01 added bash-style SELECT diff -r 4e9011c3f732 -r 1941e54cb776 cmd2.py --- 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): diff -r 4e9011c3f732 -r 1941e54cb776 example/example.py --- a/example/example.py Thu Jan 28 08:52:04 2010 -0500 +++ b/example/example.py Fri Jan 29 10:32:40 2010 -0500 @@ -26,6 +26,10 @@ self.stdout.write('\n') # self.stdout.write is better than "print", because Cmd can be # initialized with a non-standard output destination + def do_sel(self, arg): + opts = arg.split() + result = self.select(opts) + self.poutput('yay for %s' % result) do_say = do_speak # now "say" is a synonym for "speak" do_orate = do_speak # another synonym, but this one takes multi-line input