pythoninputraw-inputreplay

Python user input replay


How can I get the last raw_input? My py asks questions(raw_input) and if user types wrong asks the same again and user needs to type all over again, so how can I get last input to make de user just edit it??(like a shell pressing key-up)


Solution

  • You are looking for the readline module. Here's an example from effbot.org:

    # File: readline-example-2.py
    
    class Completer:
        def __init__(self, words):
            self.words = words
            self.prefix = None
        def complete(self, prefix, index):
            if prefix != self.prefix:
                # we have a new prefix!
                # find all words that start with this prefix
                self.matching_words = [
                    w for w in self.words if w.startswith(prefix)
                    ]
                self.prefix = prefix
            try:
                return self.matching_words[index]
            except IndexError:
                return None
    
    import readline
    
    # a set of more or less interesting words
    words = "perl", "pyjamas", "python", "pythagoras"
    
    completer = Completer(words)
    
    readline.parse_and_bind("tab: complete")
    readline.set_completer(completer.complete)
    
    # try it out!
    while 1:
        print repr(raw_input(">>> "))