【问题标题】:Catch socket timeout exception捕获套接字超时异常
【发布时间】:2011-11-02 06:50:54
【问题描述】:

我想捕获套接字超时(最好是在异常中)...except urllib.error.URLError: 可以捕获它,但我需要区分死链接和超时...。如果我取出 except urllib.error.URLError:套接字超时未捕获,脚本以 socket.timeout 错误终止

import urllib.request,urllib.parse,urllib.error
import socket
import http
socket.setdefaulttimeout(0.1)


try:
    file2 = urllib.request.Request('http://uk.geforce.com/html://')
    file2.add_header("User-Agent","Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.29 Safari/525.13")
    file3 = urllib.request.urlopen(file2).read().decode("utf8", 'ignore')
except urllib.error.URLError: print('fail')
except socket.error: print('fail')
except socket.timeout: print('fail')
except UnicodeEncodeError: print('fail')
except http.client.BadStatusLine: print('fail')
except http.client.IncompleteRead: print('fail')
except urllib.error.HTTPError: print('fail')

print('done')

【问题讨论】:

    标签: python sockets timeout python-3.x


    【解决方案1】:
    ...
    except urllib.error.URLError, e:
        print type(e.reason)
    

    只要有套接字超时,您就会看到<class 'socket.timeout'>。这是你想要的吗?

    例如:

    try:
      data = urllib2.urlopen("http://www.abcnonexistingurlxyz.com")
    except Exception,e:
      print type(e.reason)
    ... 
    <class 'socket.timeout'>
    

    【讨论】:

    • 我刚刚意识到您将问题标记为 Python-3.x。不幸的是,我无法访问 Python 3。上面的代码应该适用于 x>=3 的 2.x。
    猜你喜欢
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    • 1970-01-01
    • 2015-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多