How to catch socket timeout?

Alan Kennedy alanmk at hotmail.com
Sun Sep 21 12:41:59 EDT 2003


Peter Otten wrote:
> socket.timeout is a subclass of socket.error, so the timeout exception
> should be caught by the first except clause.

> So it seems there is *no* way to catch the error.
> I think you should file a bug report.

Hmmm.

What is wrong with the following code? It seems to do what you need:

#=======================================================
from urllib2 import urlopen
import socket
import sys

slowurl = "http://127.0.0.1/cgi-bin/longWait.py?wait=10"
socket.setdefaulttimeout(1)

try:
    data = urlopen(slowurl)
    data.read()
except socket.error:
    errno, errstr = sys.exc_info()[:2]
    if errno == socket.timeout:
        print "There was a timeout"
    else:
        print "There was some other socket error"
#==========================================================

regards,

-- 
alan kennedy
-----------------------------------------------------
check http headers here: http://xhaus.com/headers
email alan:              http://xhaus.com/mailto/alan




More information about the Python-list mailing list