6

有人可以帮我解决这个错误吗?

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 
4

1 回答 1

6

好吧,让我们问一下 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

所以我们需要 catch 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什么?谷歌打开了文档socket.gaierror上面写着,

与地址相关的错误引发此异常,对于getaddrinfo()getnameinfo()

所以 GAI 错误 = 获取地址信息错误。

于 2014-04-04T03:52:26.733 回答