1

我要做的是使用 Python 通过 Google 自定义搜索 API 下载图像。这是我第一次,也许我在用 Python 捕捉异常时犯了一些平庸的错误。

即使我遇到一些不是 10054 Connection Reset 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]而无需停止循环。这很奇怪。

4

1 回答 1

1

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")
于 2013-07-03T15:53:59.333 回答