关于Python3.6无法使用hash_ring库

最近在了解推荐系统的相关算法,在学习到一致性hash算法的时候,了解到,Python 已经有人造好轮子了,所以可以直接的使用,在使用的过程中,出现了一些错误,好在错误原因比较简单,解决的比较快,下面是错误解决方案:

如往常一样在linux的已经激活的Python虚拟环境上使用pip安装相关库hash_ring

pip install hash_ring 

在安装成功后,打开Python,使用hash_ring

from hash_ring import *

然后报错:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/__init__.py", line 5
    except ImportError, e:
                      ^
SyntaxError: invalid syntax

Python 老司机一眼就可以看出,这是Python2x的语法,到了Python3当然无法运行,但是我以为是安装出了问题,所以直接重装,小心翼翼的又重装了一次,当然咯,还是报错,于是可以判断出,是作者应该没有再更新这个库了,,,开始手动修改:

首先找到问题代码(/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/__init__.py),并且打开如下:

from hash_ring import HashRing
  
try:
    from memcache_ring import MemcacheRing
except ImportError,e:
    pass

将其修改为Python3的语法:

from hash_ring import HashRing
  
try:
    from memcache_ring import MemcacheRing
except ImportError as e:
    pass

再次运行:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/__init__.py", line 1, in <module>
    from hash_ring import HashRing
ImportError: cannot import name 'HashRing'

什么鬼?没有模块,,,于是只好手动切换到目录(/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/)查看hash_ring.py的内容:
hash_ring内容

明显可以看到,hash_ring.py下,是的确有HashRing的,那么就只能是,索引不对啦,继续修改__init__.py如下

from hash_ring.hash_ring import HashRing
  
try:
    from memcache_ring import MemcacheRing
except ImportError as e:
    pass

然后导入就没有问题了,开始使用,又发现新的问题:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/hash_ring.py", line 62, in __init__
    self._generate_circle()
  File "/home/fanzhe/env/recommend/lib/python3.6/site-packages/hash_ring/hash_ring.py", line 79, in _generate_circle
    for j in xrange(0, int(factor)):
NameError: name 'xrange' is not defined

看来要改的地方还很多啊,将所有2的语法升级到3后

"""
import math
import sys
from bisect import bisect
    hash_ring
    ~~~~~~~~~~~~~~
    Implements consistent hashing that can be used when
    the number of server nodes can increase or decrease (like in memcached).

    Consistent hashing is a scheme that provides a hash table functionality
    in a way that the adding or removing of one slot
    does not significantly change the mapping of keys to slots.

    More information about consistent hashing can be read in these articles:

    
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值