编辑:在python3.5上,geoip包似乎有问题(我发现有人报告了一个问题here),该问题与您在不同方法上的错误消息相同)。评论人士似乎在说,这个包裹看起来被遗弃了,尽管我自己还没有查过。因此,我认为这种解决方法可能是您未来的最佳选择。在
我不认为这是Linux和Windows的问题。我试图在我的Mac机上运行你的脚本,结果和你在Windows上做的一样。我试图研究一下您得到的错误,发现有一篇文章提到他们使用了另一个包,因为它支持python3。那个包是maxminddb-geolite2。在
它的格式与您使用的格式有所不同,但我的代码如下:import socket
from geolite2 import geolite2
import argparse
import pprint
if __name__ == '__main__':
# 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.reader().get(ip_address)
pp = pprint.PrettyPrinter(indent=4)
if match is not None:
print("Country: " + str(match['country']['names']['en']))
print("Continent: " + str(match['continent']['names']['en']))
print("Time Zone: " + str(match['location']['time_zone']))
pp.pprint(match)
正如您所看到的,它在语法上相当相似,只是稍微有点不同。在
我的脚本输出(没有漂亮的打印):
^{pr2}$
以下是字典中漂亮的打印输出,以防您想知道我如何知道从何处获取您想要的匹配字典的输出:{ 'city': { 'geoname_id': 2964574,
'names': { 'de': 'Dublin',
'en': 'Dublin',
'es': 'Dublín',
'fr': 'Dublin',
'ja': 'ダブリン',
'pt-BR': 'Dublin',
'ru': 'Дублин',
'zh-CN': '都柏林'}},
'continent': { 'code': 'EU',
'geoname_id': 6255148,
'names': { 'de': 'Europa',
'en': 'Europe',
'es': 'Europa',
'fr': 'Europe',
'ja': 'ヨーロッパ',
'pt-BR': 'Europa',
'ru': 'Европа',
'zh-CN': '欧洲'}},
'country': { 'geoname_id': 2963597,
'iso_code': 'IE',
'names': { 'de': 'Irland',
'en': 'Ireland',
'es': 'Irlanda',
'fr': 'Irlande',
'ja': 'アイルランド',
'pt-BR': 'Irlanda',
'ru': 'Ирландия',
'zh-CN': '爱尔兰'}},
'location': { 'latitude': 53.3331,
'longitude': -6.2489,
'time_zone': 'Europe/Dublin'},
'registered_country': { 'geoname_id': 2963597,
'iso_code': 'IE',
'names': { 'de': 'Irland',
'en': 'Ireland',
'es': 'Irlanda',
'fr': 'Irlande',
'ja': 'アイルランド',
'pt-BR': 'Irlanda',
'ru': 'Ирландия',
'zh-CN': '爱尔兰'}},
'subdivisions': [ { 'geoname_id': 7521314,
'iso_code': 'L',
'names': { 'en': 'Leinster',
'ja': 'レンスター',
'ru': 'Ленстер'}},
{ 'geoname_id': 7778677,
'names': {'en': 'Dublin City'}}]}
如果您想这样做,您只需做以下操作:import pprint # At the top of the file
pp = pprint.PrettyPrinter(indent=4) # Anywhere in scope
pp.pprint(match) # Print!
有关漂亮打印here的详细信息。在
我知道这并不能直接回答正在发生的事情,但如果我真的弄清楚了真正的问题,我会更新我的答案。在此之前,请使用以下解决方法:)。在