Mercurial > python-cmd2
changeset 310:9d91406ca3a7
select polished
author | catherine@dellzilla |
---|---|
date | Fri, 29 Jan 2010 11:26:23 -0500 |
parents | 1941e54cb776 |
children | 54e2dd53ba38 |
files | cmd2.py example/example.py |
diffstat | 2 files changed, 23 insertions(+), 10 deletions(-) [+] |
line wrap: on
line diff
--- a/cmd2.py Fri Jan 29 10:32:40 2010 -0500 +++ b/cmd2.py Fri Jan 29 11:26:23 2010 -0500 @@ -13,6 +13,7 @@ Parsing commands with `optparse` options (flags) Redirection to file with >, >>; input from file with < Easy transcript-based testing of applications (see example/example.py) +Bash-style ``select`` available Note that redirection with > and | will only work if `self.stdout.write()` is used in place of `print`. The standard library's `cmd` module is @@ -836,16 +837,32 @@ 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.''' + the bash shell's SELECT. Returns the item chosen. + + Argument ``options`` can be: + a single string -> will be split into one-word options + a list of strings -> will be offered as options + a list of tuples -> interpreted as (value, text), so + that the return value can differ from + the text advertised to the user ''' if isinstance(options, basestring): - options = options.split() - for (idx, opt) in enumerate(options): - self.poutput(' %2d. %s\n' % (idx+1, opt)) + options = zip(options.split(), options.split()) + fulloptions = [] + for opt in options: + if isinstance(opt, basestring): + fulloptions.append((opt, opt)) + else: + try: + fulloptions.append((opt[0], opt[1])) + except IndexError: + fulloptions.append((opt[0], opt[0])) + for (idx, (value, text)) in enumerate(fulloptions): + self.poutput(' %2d. %s\n' % (idx+1, text)) while True: response = raw_input(prompt) try: response = int(response) - result = options[response - 1] + result = fulloptions[response - 1][0] break except ValueError: pass # loop and ask again
--- a/example/example.py Fri Jan 29 10:32:40 2010 -0500 +++ b/example/example.py Fri Jan 29 11:26:23 2010 -0500 @@ -25,11 +25,7 @@ self.stdout.write(arg) 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) + # initialized with a non-standard output destination do_say = do_speak # now "say" is a synonym for "speak" do_orate = do_speak # another synonym, but this one takes multi-line input