socket.rcv timeout while-loop

Stephen Hansen me+list/python at
Thu Feb 3 19:53:01 CET 2011

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.

  timeout = s.gettimeout()

Personally, I'd prefer to do:

with timeout(s, 3):

That's a lot more clear, and I'd roll this context manager to accomplish it:

--- start

from contextlib import contextmanager

def timeout(sock, timeout):
    old_timeout = sock.gettimeout()
        yield sock

--- 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


   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog:

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <>

More information about the Python-list mailing list