non blocking read()

Pierre Barbier de Reuille pierre.barbier at cirad.fr
Thu Dec 2 11:57:04 CET 2004


Steve Holden a écrit :
> Donn Cave wrote:
> 
>> In article <mailman.6995.1101939055.5135.python-list at python.org>,
>>  Gustavo Córdova Avila <gustavo.cordova at q-voz.com> wrote:
>>
>>
>>> David Bolen wrote:
>>>
>>>
>>>> Jp Calderone <exarkun at divmod.com> writes:
>>>>
>>>>
>>>>>   def nonBlockingReadAll(fileObj):
>>>>>       bytes = []
>>>>>       while True:
>>>>>           b = fileObj.read(1024)
>>>>>           bytes.append(b)
>>>>>           if len(b) < 1024:
>>>>>               break
>>>>>       return ''.join(bytes)
>>>>>
>>>>
>>>> Wouldn't this still block if the input just happened to end at a
>>>> multiple of the read size (1024)?
>>>>
>>>> -- David
>>>>
>>>
>>> No, it'll read up to 1024 bytes or as much as it can, and
>>> then return an apropriatly sized string.
>>
>>
>>
>> Depends.  I don't believe the original post mentioned
>> that the file is a pipe, socket or similar, but it's
> 
> 
> It did actually specifically mention files.
> 
Read more carrefully and you'll see that it mentionned "file object" and 
, on UNIX systems, that's very different than "file". It even mentions 
"stdin", and stdin (though not always a pipe) always bahaves like a pipe 
when it comes to non-blocking reading.

For an answer, you can modify stdin (or whatever file desciptor you 
have) to have non-blocking reading operations. It can be done using :

*****************
import fcntl, os
fcntl.fcntl(0, fcntl.F_SETFL, os.O_NONBLOCK)
*****************

You can replace the "0" by whatever file descriptor you want of course !
After that call stdin is non-blocking.

Pierre



More information about the Python-list mailing list