Alarms in threads - how to get/mimic?

Lloyd Zusman ljz at asfast.com
Sat Dec 16 22:56:03 EST 2000


Luca de Alfaro <dealfaro at eecs.berkeley.edu> writes:

> [ ... ]
> 
> What is not clear to me is the following.  When there is a timeout,
> the exception Timeout is not caught by httplib.  Hence, if the thread
> that called httplib just continues its job giving up on the
> connection, httplib will not have a chance to do any clean-up, such as
> for example releasing/closing the socket. 
> 
> Hence, it seems to me that in order to abort a web page load cleanly
> upon timeout, I also have to modify the httplib module to handle the
> exception Timeout, and do clean-up work if that happens. 
> 
> Is my understanding correct? 

Not entirely.  When using timeoutsocket, all you have to do is start
catching timeout exceptions when you make the various method calls
within httplib.  As an example, I'll illustrate the use of
timeoutsocket with some sample code that I've based on a program of
mine that uses imaplib.  You could do exactly the same kind of thing
when using httplib:

   import sys, traceback, imaplib
   import timeoutsocket    # this needs to be imported prior to
                           # making any socket calls

   # ... snip ...

   # the following line sets a 15 second timeout for the
   # subsequent socket calls made within imaplib

   timeoutsocket.setDefaultSocketTimeout(15.0)

   try:
      connection = imaplib.IMAP4(host)
   except timeoutsocket.Timeout, msg:
      # this "except" block will be invoked if the
      # imaplib initialization fails
      print "imap initialization timed out"
   except:
      # this "except" block will be invoked if there
      # is any other exception that occurs during
      # imap initialization
      typ, val, tb = sys.exc_info()
      print "imap initialization exception: %s %s\ntraceback:" % \
         ( typ, val )
      traceback.print_tb(tb)
   else:
      # the imaplib connection is successful      
      print "successful imaplib connection"

It's recommended in Python that exception handling be done whenever
it's appropriate; therefore, by wrapping your httplib calls in this
same manner, you'll remain true to the Pythonic Way, and you won't
have to re-write any httplib code when using timeoutsocket.

Note that the timeoutsocket.setDefaultSocketTimeout() method call
should be made before making any httplib calls.  If you want to use
different timeout values when making different httplib calls (or other
calls socket-based methods), you'll have to re-invoke the
setDefaultSocketTimeout() method before each call that uses a changed
timeout value.

HTH

- Lloyd


-- 
 Lloyd Zusman
 ljz at asfast.com



More information about the Python-list mailing list