2008-12-05 84 views
2

我一直在努力让2.5模块移植到3.0,主要是为了我自己的教育,当我陷入困境时。类 “生成器” 作为其初始化:有关3.0的“hashlib”模块的问题

def __init__(self, **options): 
    self._verifyOptions(options) 
    self._options = options 
    self._initDigest() 
    self._initBuildNames() 
    self._methods = [] 

但在出现错误:

def _initDigest(self): 
    import os, sys, hashlib 
    digester = hashlib.md5() 
    digester.update(self._options.get('code')) 
    self._digest = digester.hexdigest() 

它有它的回溯:

Traceback (most recent call last): 
    File "<pyshell#5>", line 5, in <module> 
    """, language="Cee") 
    File "C:\Python30\lib\site-packages\PyInline\__init__.py", line 31, in build 
    b = m.Builder(**args) 
    File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 17, in __init__ 
    self._initDigest() 
    File "C:\Python30\lib\site-packages\PyInline\Cee.py", line 27, in _initDigest 
    digester.update(self._options.get('code')) 
TypeError: object supporting the buffer API required 

我已经通过2to3运行它,但它并没有采取它。据我所知,更新函数期望的参数是以字节/缓冲区的形式,但我已经尝试了几种不同的方法来转换它,并没有成功。

一如既往,任何援助将不胜感激。 :)

回答

4

我猜这条线:

digester.update(self._options.get('code')) 

应该变成:

digester.update(self._options.get('code').encode("utf-8")) 

实际所需的编码可能是你的情况不同,但UTF-8将在所有情况下工作。

+0

您已成功纠正此错误,并在此任务中进一步教育我。我祝贺并感谢你! – 2008-12-05 09:18:24

0

我还没试过3.0。但是现在字节序列和字符串之间有更大的区别。后者保存unicode代码点,而前者不保存unicode,但只保存unicode字符串encoded。哈希运算字节序列。所以你必须首先编码你的(unicode)字符串,然后把它们送到哈希处。