views:

93

answers:

2

I want someone to type words in the console, and autocomplete from a list when they hit "tab" key. However, raw_input won't return a string until someone hits [Enter].

How do I read characters into a variable until the user hits [Enter]?

*Note: I don't want to use import readline for autocompletion because of OS issues.

+1  A: 

On *nix use select on sys.stdin to wait for a character, then .read() it in. On Windows use msvcrt.kbhit() and msvcrt.getch().

Ignacio Vazquez-Abrams
Could you elaborate on this solution? I failed to implement it, being unfamiliar with the select module… :/
EOL
@EOL: What does "unfamiliar" mean? Perhaps you should (1) write some code then (2) ask a separate question on any specific problems you have with that code.
S.Lott
@S.Lott: The following code does not catch the first character, but waits until enter is pressed: `import select, sys; char = select.select([sys.stdin], [], [])[0][0].read(1); print "Read %s" % char`. Maybe this is due to the fact that I'm unfamiliar with the `select` module, and do not know how to use it. :)
EOL
+3  A: 

There is an official FAQ entry on this question, for Unix: http://www.python.org/doc/faq/library/#how-do-i-get-a-single-keypress-at-a-time

Edit (copied from Donal Fellows' comment below): "The problem is that the terminal is in “cooked” mode by default (allowing simple line editing) and that to get the keys as they're typed, it has to be placed in “raw” mode." (Thanks!)

EOL
Definitely the right answer. You might want to edit in that the problem is that the terminal is in “cooked” mode by default (allowing simple line editing) and that to get the keys as they're typed, it has to be placed in “raw” mode. And that at that point the questioner also has to worry about bad typing and other things like that which the OS usually does for them.
Donal Fellows