cmd.Cmd asking questions?

Robert Kern robert.kern at gmail.com
Mon Nov 28 07:27:50 EST 2011


On 11/28/11 12:12 PM, Tim Chase wrote:
> Are there best-practices for creating wizards or asking various questions
> (whether yes/no or text/numeric entry) in a cmd.Cmd class? Something like the
> imaginary confirm() and get_string() methods here:
>
> class MyCmd(cmd.Cmd):
> def do_name(self,line):
> s = get_string(prompt=line, default="Whatever")
> ...
> def do_save(self,line):
> if os.path.isfile(line):
> if not confirm("%r exists. Continue?", True): return
> self.save(line)
> def save(self, filename):
> ...
>
> I can monkey with printing messages and using raw_input(), but I'd like to know
> if there's a better way (such as something interacting with readline for
> text-entry-with-history-and-completion,

If you import readline, then any following uses of raw_input() will 
automatically use readline. You may want to swap out the history when you use 
get_string() or confirm() so they don't mess up the regular Cmd history, but the 
basic functionality should work out-of-box.

> or raw-character input for Y/N answers
> rather than the need to hit <enter>, making it feel more uniform),

I actually have a preference for needing to press enter for Y/N answers, too. 
It's distinctly *less* uniform to have some questions requiring an enter and 
some not. It can be unpleasantly surprising to the user, too.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco




More information about the Python-list mailing list