连接重置由Peer与Python模块urllib

时间:2013-07-03 15:39:29

标签: python python-3.x urllib google-custom-search

我尝试做的是使用Python通过Google Custom Search API下载图片。这是我的第一次,也许我正在做一些平庸的错误,用Python捕捉异常。

即使我遇到一些不是10054 Connection By Peer的错误,一切正常。代码是这样的,我刚刚拿出了无用的部分:

try: 
    urllib.request.urlretrieve(myUrl['link'],str(count)+'.jpg')
except URLError as e:
    print(e.reason)

有时会发生连接被对等方重置,并且控制台显示此错误。

urllib.request.urlretrieve(myUrl['link'],str(count)+'.jpg')
File "C:\Python33\lib\urllib\request.py", line 210, in urlretrieve
   block = fp.read(bs)
File "C:\Python33\lib\http\client.py", line 503, in read
   return super(HTTPResponse, self).read(amt)
File "C:\Python33\lib\http\client.py", line 542, in readinto
   n = self.fp.readinto(b)
File "C:\Python33\lib\socket.py", line 297, in readinto
   return  self._sock.recv_into(b)
   ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
   Press any key to continue . . .

现在我真的不想让这个URL工作,但我只想让我的循环继续前进而不是停止。我怎么能抓住这个例外?

编辑:

我还注意到,有时代码正确捕获错误,print(e.reason)正确输出[WinError 10054]而不停止循环。这很奇怪。

1 个答案:

答案 0 :(得分:1)

如果您不知道确切的问题,可以捕获所有异常:

try: 
    urllib.request.urlretrieve(myUrl['link'],str(count)+'.jpg')
except URLError as e:
    print(e.reason)
except KeyboardInterrupt as ki:
    raise ki
except:
    print("Unknown Error")