简体   繁体   English

Peer使用Python模块urllib重置连接

[英]Connection Reset by Peer with Python module urllib

What I'm tryng to do is to download images through Google Custom Search API using Python. 我想做的是使用Python通过Google自定义搜索API下载图像。 It's my first time and maybe I'm making some banal error catching exceptions with Python. 这是我的第一次,也许我正在做一些普通的错误来捕获Python的异常。

It all works fine even when I get into some error which is not 10054 Connection Reset By Peer. 即使遇到一些不是10054 Connection Peer Reset by Peer的错误,也可以正常工作。 The code is something like this, I've just taken out the useless part: 代码是这样的,我刚刚删除了无用的部分:

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

Sometimes it happens that connection is reset by peer and the console shows this error. 有时,连接会被对等方重置,并且控制台会显示此错误。

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 . . .

Now I'm not really interested in make that URL work, but I just want my loop to keep going and not to stop. 现在,我对使该URL正常运行并不真正感兴趣,但是我只希望我的循环继续进行而不是停止。 How can I catch that exception? 我如何捕获该异常?

Edit: 编辑:

I also noticed that sometimes the code correctly catches the error and print(e.reason) correctly outputs [WinError 10054] without stopping the loop. 我还注意到有时代码可以正确捕获错误,并且print(e.reason)正确输出[WinError 10054]而无需停止循环。 That's very strange. 真奇怪

If you don't know the exact problem, you can catch all exceptions as so: 如果您不知道确切的问题,可以这样捕获所有异常:

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")

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

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