Saturday, November 21, 2009

Sometimes it is more appropriate to read from keyboard without waiting for Enter to be codessed, for example, when choosing from a menu. The raw_input("Prompt String >") always waits for Enter, so a function similar to getch() in C is needed and there are some solutions for that in Python.

There is getch() equivalent for Windows environment in library msvcrt:import msvcrt

result = msvcrt.getch()

Funny thing is that the code works fine from command window (cmd.exe), but does not in IDLE: in IDLE it does not wait for a key and gives out '\xff' as the result.

Since the solution is system dependent some people propose a universal approach when program tries one implementation and if it fails - the other one, here is an example from ActiveState Code, Danny Yoo:class _Getch: """Gets a single character from standard input. Does not echo to the screen.""" def __init__(self): try: self.impl = _GetchWindows() except ImportError: self.impl = _GetchUnix()

It works OK in Windows command window (cmd.exe), but in IDLE and Linux the line root.withdraw() should be commented out - the code works OK while the root window is in focus. This kind of examples you can find here.

Curses library has its own getch implementation. I did not check it, just would like to mention for the record.

If you know any other solutions - I'd love to here from you about them!