2017-08-01 34 views
-1

我與嘗試掙扎,除了與Python 3如何捕捉具有的urllib(python3)超時錯誤

我能趕上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 

回答

2

關於Python 3 .x,TimeoutError是內建的異常類。你可以用

except TimeoutError: 
    ... 

關於Python 2.x的抓住它,你有兩個選擇:

  1. urllib.socket.timeout例外

  2. requests.Timeout例外

+0

它適用於Python 3.5。非常感謝你 – whitebear

+0

@whitebear添加了一些糖。如果有幫助,您可以將其標記爲已接受。謝謝。 –

+0

對不起,我錯過了接受檢查 – whitebear

0

您需要在使用它之前導入插座:

from urllib import socket 

或指定你在談論的插座來自urllib的,即:

except urllib.socket.timeout as e: 
+0

ImportError:不能導入名稱「套接字」我已經嘗試了上面的一個,並碰到這個錯誤。 – whitebear

+0

你是否試圖從這裏運行代碼:https://stackoverflow.com/questions/2712524/handling-urllib2s-timeout-python – Stael

+0

也許他們已經在python 3中更改它,但評論表明你不需要套接字,URLerror捕獲兩者。 – Stael