有人可以帮助我如何捕获这个错误吗?

import pygeoip  
gi = pygeoip.GeoIP('GeoIP.dat')  
print gi.country_code_by_name('specificdownload.com')  

Traceback (most recent call last):  
  File "<module1>", line 14, in <module>  
  File "build\bdist.win-amd64\egg\pygeoip\__init__.py", line 447, in country_code_by_name  
    addr = self._gethostbyname(hostname)  
  File "build\bdist.win-amd64\egg\pygeoip\__init__.py", line 392, in _gethostbyname  
    return socket.gethostbyname(hostname)  
gaierror: [Errno 11001] getaddrinfo failed 

答案

好吧,让我们问Python是什么类型的例外:

#!/usr/bin/env python2.7

import pygeoip
gi = pygeoip.GeoIP('GeoIP.dat')
try:
    print gi.country_code_by_name('specificdownload.com')
except Exception, e:
    print type(e)
    print e

印刷:

$ ./foo.py
<class 'socket.gaierror'>
[Errno 8] nodename nor servname provided, or not known

所以我们需要抓住socket.gaierror,这样:

#!/usr/bin/env python2.7

import pygeoip
import socket
gi = pygeoip.GeoIP('GeoIP.dat')
try:
    print gi.country_code_by_name('specificdownload.com')
except socket.gaierror:
    print 'ignoring failed address lookup'

尽管仍然存在一个问题,到底是什么gaierror?Google出现了socket.gaierror文档,说,

对于地址相关的错误而提出了此例外getaddrinfo()getnameinfo()

因此,GAI错误=获取地址信息错误。

来自: stackoverflow.com