blocking read on stdin on Windows?

Jeff Learman jlearman at cisco.com
Sat Sep 4 16:35:00 EDT 2004


Hmm, getch() and getche() don't block.

The lib ref page says, "Read a keypress and return the resulting 
character. Nothing is echoed to the console. This call will block if a 
keypress is not already available, but will not wait for Enter to be 
pressed."  However:

	import msvcrt

	print msvcrt.kbhit()
	print "prompt: ",
	ch = msvcrt.getche()
	print
	print ord(ch)

Results -- without typing a key:

	0
	prompt:
	255

Any ideas?

Thanks,
Jeff

Dennis Lee Bieber wrote:

> On Sat, 04 Sep 2004 11:23:12 -0400, Jeff Learman <jlearman at cisco.com>
> declaimed the following in comp.lang.python:
> 
> 
>>I want to do a very simple thing in Windows.  (Using Python Shell.)
>>
>>I want to write a prompt to sys.stdout and read the user input.
>>(Ideally, without waiting for a newline.)
>>
> 
> 	Library reference
> 	Section 22 (M$ specific)
> 	Subsection .1.2 (Console I/O)
> 
> lib> kbhit( ) 
> lib> Return true if a keypress is waiting to be read. 
> lib> 
> lib> getch( ) 
> lib> Read a keypress and return the resulting character. Nothing is
> echoed to the console. This call will block if a keypress is not already
> available, but will not wait for Enter to be pressed. If the pressed key
> was a special function key, this will return '\000' or '\xe0'; the next
> call will return the keycode. The Control-C keypress cannot be read with
> this function. 
> lib> 
> lib> getche( ) 
> lib> Similar to getch(), but the keypress will be echoed if it
> represents a printable character. 
> lib> 
> lib> putch( char) 
> lib> Print the character char to the console without buffering. 
> lib> 
> lib> ungetch( char) 
> lib> Cause the character char to be ``pushed back'' into the console
> buffer; it will be the next character read by getch() or getche(). 
> 
> 	stdin tends to be buffered by the OS -- the OS doesn't release
> anything until the new-line. You have to use OS specific operations to
> get to the data in the buffer.
> 




More information about the Python-list mailing list