python-geoip在python3.4上不起作用?

时间:2015-09-15 00:00:53

标签: python geoip geolite2

我能够让geolite2在python2.7上运行 - 但我需要3.4。我在此链接上找到了2.7的说明:http://pythonhosted.org/python-geoip/。还提供了代码片段。

pip install python-geoip
pip install python-geoip-geolite2
>>> from geoip import geolite2
>>> match = geolite2.lookup('17.0.0.1')
>>> match is not None
True

所以我自然地将所有pip改为pip3并安装在一个新的VM上。代码没有错误,但它不会从db中返回并返回值。

pip3 install python-geoip
pip3 install python-geoip-geolite2

在2.7 VM中,当我使用3.4时,我将geoip lib指向/usr/local/lib/python2.7/dist-packages - 也没有运气。然而,它在同一个VM上运行2.7。

我需要做些什么才能让它在3.4上工作?

4 个答案:

答案 0 :(得分:3)

python-geoip不支持Python 3,并且在两年内没有更新。虽然有一个pull request来添加Python 3支持,但我不希望它很快被合并和发布。我建议改为使用official MaxMind geoip2 package

答案 1 :(得分:1)

安装:

apt install python3-pip
pip3 install maxminddb 
pip3 install maxminddb-geolite2

示例用法:

#!/usr/bin/python3
# coding: utf8
from geolite2 import geolite2
reader = geolite2.reader()
# google ip
match = reader.get('172.217.16.163')
if(match is not None):
  # print(match)
  if('country' in match):
    print(match['country']['iso_code'])
  else:
    print(match['continent']['code'])
else:
  print("") 

答案 2 :(得分:0)

python-geoip,具有python 3支持(通过pippip3安装):

pip3 install python-geoip-python3

输出:

Collecting python-geoip-python3
  Downloading python_geoip_python3-1.3-py2.py3-none-any.whl (7.4 kB)
Installing collected packages: python-geoip-python3
Successfully installed python-geoip-python3-1.3

geolite2

pip3 install python-geoip-geolite2

输出:

Successfully built python-geoip-geolite2
Installing collected packages: python-geoip-geolite2
Successfully installed python-geoip-geolite2-2015.303

test_geoip.py的示例:

#!/usr/bin/env python3

import socket
from geoip import geolite2
import argparse
import json

# Setup commandline arguments
parser = argparse.ArgumentParser(description='Get IP Geolocation info')
parser.add_argument('--hostname', action="store", dest="hostname", required=True)

# Parse arguments
given_args = parser.parse_args()
hostname = given_args.hostname
ip_address = socket.gethostbyname(hostname)

print("IP address: {0}".format(ip_address))

match = geolite2.lookup(ip_address)

if match is not None:
    print('Country: ',match.country)
    print('Continent: ',match.continent)
    print('Time zone: ', match.timezone)
    print('Location: ', match.location)

运行:

python3 test_geoip.py --hostname=amazon.co.uk

输出:

IP address: 178.236.7.220
Country:  IE
Continent:  EU
Time zone:  Europe/Dublin
Location:  (53.3478, -6.2597)

再次运行:

python3 test_geoip.py --hostname=amazon.co.uk

输出:

IP address: 54.239.34.171
Country:  US
Continent:  NA
Time zone:  America/Los_Angeles
Location:  (47.6103, -122.3341)

答案 3 :(得分:-1)

要使用maxmind数据库:

安装:

maxminddb 
maxminddb-geolite

在您的代码中:

from geolite2 import geolite2

match = geolite2.reader()
geoip = match.get('xxx.xxx.xxx.xxx')