How to use gnu readline library in program?

Grant Edwards grante at visi.com
Tue Jul 1 14:14:54 EDT 2008


>> What I want to do is replace sys.stdin.readline() with
>> something that will provide the user with line editing and
>> history recall.  In other languages, one uses the Gnu readline
>> library to do that, but my reading of the Python library
>> documentation is that's not what the Python readline module is
>> for. Am I wrong?
>
> Here's a simple example:
>  
> import readline
>
> for s in "alpha beta gamma".split():
>     readline.add_history(s)
>
> candidates = "red yellow pink blue black".split()
>
> def completer(word, index):
>     matches = [c for c in candidates if c.startswith(word)]
>     try:
>         return matches[index] + " "
>     except IndexError:
>         pass
>
>
> readline.set_completer(completer)
> readline.parse_and_bind("tab: complete")
>
> while 1:
>     print raw_input("$ ")

Ah, thanks.  It was far too simple.  What I was looking for was
simply:

  import readline

then replace sys.stdin.readline() with raw_input()

> You may also consider using the cmd module.

I'll have to keep the cmd module in mind for other applications
(where the user is entering commands).  Rather than commands,
the user of this application is entering data that changes
little (if any) from one line to the next, so raw_input() is
exactly what I needed.

-- 
Grant Edwards                   grante             Yow! I'm young ... I'm
                                  at               HEALTHY ... I can HIKE
                               visi.com            THRU CAPT GROGAN'S LUMBAR
                                                   REGIONS!



More information about the Python-list mailing list