Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #55943 > unrolled thread

Re: socket.rcv timeout while-loop

Started byStephen Hansen <me+list/python@ixokai.io>
First post2011-02-03 10:53 -0800
Last post2011-02-03 10:53 -0800
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: socket.rcv timeout while-loop Stephen Hansen <me+list/python@ixokai.io> - 2011-02-03 10:53 -0800

#55943 — Re: socket.rcv timeout while-loop

FromStephen Hansen <me+list/python@ixokai.io>
Date2011-02-03 10:53 -0800
SubjectRe: socket.rcv timeout while-loop
Message-ID<mailman.1629.1296759197.6505.python-list@python.org>

[Multipart message — attachments visible in raw view] — view raw

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/

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web