繁体   English   中英

如何使用urllib捕获超时错误

[英]How to catch timeout error with urllib

我正在尝试尝试,但python 3除外

我可以捕获HTTPError(错误请求)和URLError(找不到主机/路由名称)

但是我还没赶上超时错误。

 while True:
        try:
            f = urllib.request.urlretrieve(url,csvname)
        except urllib.error.HTTPError as e: #
            print(str(chl) + " Error:" + str(e))


            continue
        except urllib.error.URLError as e: 
            continue
        except socket.timeout as e:
            #I can't catch time out error here
            continue

它返回这个。

如何防止脚本因超时错误而停止?

Traceback (most recent call last):
  File "wisdom2.py", line 84, in <module>
    f = urllib.request.urlretrieve(url,csvname)
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/urllib/request.py", line 186, in urlretrieve
    with contextlib.closing(urlopen(url, data)) as fp:
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/urllib/request.py", line 464, in open
    response = self._open(req, data)
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/urllib/request.py", line 482, in _open
    '_open', req)
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/urllib/request.py", line 442, in _call_chain
    result = func(*args)
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/urllib/request.py", line 1211, in http_open
    return self.do_open(http.client.HTTPConnection, req)
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/urllib/request.py", line 1186, in do_open
    r = h.getresponse()
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/http/client.py", line 1227, in getresponse
    response.begin()
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/http/client.py", line 386, in begin
    version, status, reason = self._read_status()
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/http/client.py", line 348, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/Users/whitebear/.pyenv/versions/3.4.6/lib/python3.4/socket.py", line 378, in readinto
    return self._sock.recv_into(b)
TimeoutError: [Errno 60] Operation timed out

     except socket.timeout as e:
NameError: name 'socket' is not defined

在python 3.x上, TimeoutError是内置的异常类。 你可以抓住它

except TimeoutError:
    ...

在python 2.x上,您有两个选择:

  1. 捕获urllib.socket.timeout异常

  2. 捕获requests.Timeout超时异常

您需要先导入套接字,然后才能使用它:

from urllib import socket

或指定您要谈论的套接字来自urllib,即:

except urllib.socket.timeout as e:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM