read stdin NON-BLOCKING

Martin von Loewis loewis at informatik.hu-berlin.de
Tue Sep 25 08:28:31 EDT 2001


"Olivier Deme" <olivier.deme at airtel-atn.com> writes:

> How can I read the standard input in a non-blocking way?
> I have tried the following, but it is still blocking:
> 
>         fcntl.fcntl(sys.stdin.fileno(), FCNTL.F_SETFD, FCNTL.O_NONBLOCK)
>         os.read(sys.stdin.fileno(), bufsize)

When you say 'blocking', do you mean 'line-buffered'? Are you using a
Unix system? This would be something your terminal does, to allow
editing of the current line. The data will appear in sys.stdin only
when enter is pressed.  This is also known as the "cooked" mode of
terminal operation. You need to set it into the "raw" mode:

import os,sys
os.system("stty raw")
while 1:
    s = sys.stdin.read(1)
    print "Got",s

The effect of "stty raw" can also be achieved without starting an
external program, by means of fcntl.ioctl or termios.tcsetattr. I
don't know which specific parameters to use, though - if you find out,
could you please post them?

Regards,
Martin




More information about the Python-list mailing list