socket.rcv timeout while-loop

Dwayne Blind dwayneblind at gmail.com
Fri Feb 4 00:23:07 CET 2011


The solution would be

     timeout = s.gettimeout()
     s.settimeout(3)
     b=time.clock()
     while time.clock()-b<3 :
          try :
               data=s.recv(1024)
          except :
               break
     s.settimeout(timeout)

Am I right ?

Dwayne

2011/2/4 Dwayne Blind <dwayneblind at gmail.com>

> Thanks Stephen. It's really nice of you.
>
> I have not understood everything though. (I have never used a context
> manager before.)
>
> Here are some comments :
>
>      timeout = s.gettimeout()    # Is that the default timeout ?
>      s.settimeout(3) # I guess this is a 3 second timeout
>      s.recv(1024)
>      s.settimeout(timeout) # You change it back ?
>
> So with a while loop, it should be :
>
>
>      timeout = s.gettimeout()
>      s.settimeout(3)
>      b=time.clock()
>      while time.clock()-b<3 :
>
>           data=s.recv(1024)
>      s.settimeout(timeout)
>
> Am I right ?
>
> Thanks again,
> Dwayne
>
>
> 2011/2/3 Stephen Hansen <me+list/python at ixokai.io>
>
>> On 2/3/11 10:13 AM, Dwayne Blind wrote:
>>
>> > Thanks for your answer. I don't want to reset my socket. I want to apply
>> > the timeout to the rcv method only.
>>
>> Setting the timeout does not "reset [your] socket", I don't think. And I
>> get that you want to only timeout recv... that's why I pointed out its a
>> socket method, not an argument to recv. If you don't want it to apply to
>> everything else, you just have to be sure to change it back after recv.
>>
>> Just:
>>  timeout = s.gettimeout()
>>  s.settimeout(3)
>>  s.recv(1024)
>>  s.settimeout(timeout)
>>
>> Personally, I'd prefer to do:
>>
>> with timeout(s, 3):
>>    s.recv(1024)
>>
>> That's a lot more clear, and I'd roll this context manager to accomplish
>> it:
>>
>> --- start
>>
>> from contextlib import contextmanager
>>
>> @contextmanager
>> def timeout(sock, timeout):
>>    old_timeout = sock.gettimeout()
>>    sock.settimeout(timeout)
>>    try:
>>        yield sock
>>    finally:
>>        sock.settimeout(old_timeout)
>>
>> --- end
>>
>> The contextmanager decorator is an easy/quick way of making a context
>> manager. Everything up until the yield is executed before the 'with'
>> block is run, and everything after the yield is executed after the
>> 'with' block concludes.
>>
>> If the with block throws an exception, it'll be catchable at the yield
>> point.
>>
>> --
>>
>>   Stephen Hansen
>>   ... Also: Ixokai
>>   ... Mail: me+list/python (AT) ixokai (DOT) io
>>   ... Blog: http://meh.ixokai.io/
>>
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110204/507256cb/attachment.html>


More information about the Python-list mailing list