How to use gnu readline library in program?
Peter Otten
__peter__ at web.de
Tue Jul 1 11:58:33 EDT 2008
Grant Edwards wrote:
> I'm trying to figure out how to use the gnu readline library so
> that when my program is prompting the user for input there is
> line editing and history support.
>
> I've read and re-read the documentation for the "readline"
> module in the standard library and I still can't figure out how
> to use the module or even if the module is intended to do what
> I want. The example code all seems to be about on how to
> modify the behavior of an interactive Python interpreter
> session so you have things like auto-completion of Python
> identifiers.
>
> 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("$ ")
You may also consider using the cmd module.
Peter
More information about the Python-list
mailing list