Mercurial > python-cmd2
changeset 309:1941e54cb776
added bash-style SELECT
author | catherine@dellzilla |
---|---|
date | Fri, 29 Jan 2010 10:32:40 -0500 |
parents | 4e9011c3f732 |
children | 9d91406ca3a7 |
files | cmd2.py example/example.py |
diffstat | 2 files changed, 26 insertions(+), 1 deletions(-) [+] |
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):
--- 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