tags:

views:

18

answers:

0

I have a command line mini-app written in Python 2.7 that has a "press any key" style prompt, but that responds differently depending on what kind of key the user types.

If they type a character, then that character will become the first character of the search query. I don't want the user to have to type a character to indicate "I'm doing a search now," whatever first character was typed should be the first character of the search item.

The code below works as advertised (using the getch recipe here), but the major shortcoming is that the raw_input doesn't allow the user to backspace over that first character. So that first character that's typed cannot be undone. That sucks. Worse, the getch recipe doesn't seem to "return" any backspace characters the user types, making an easy fix work-around a real head-scratcher.

Is there a way to do this using a simple hack, or do I really need to learn curses to do it?

I'd like to keep the raw_input line because I also want tab completion and up arrow history using the readlines module.

import getch

class Any_Key_Dispatch(object):

    def __call__(self, prompt):
        character = getch.getch()
        remember = ''
        if character != ' ':
            remember = character
        if remember:
            prompt = prompt + remember
        result = raw_input(prompt)
        if remember:
            result = remember + result
        return result