MD5模块错误

5

我正在使用一个较旧版本的PLY,其中包含md5模块(以及其他模块):

import re, types, sys, cStringIO, md5, os.path

尽管脚本运行,但仍存在以下错误:

DeprecationWarning: the md5 module is deprecated; use hashlib instead

我该如何修复这个错误,让它不再出现?

谢谢。


2
那里面有问题吗? - Ignacio Vazquez-Abrams
如何修复它以消除错误? - eozzy
你不能使用sha1代替md5吗?不推荐使用md5。 - Anders
6个回答

10

已经尝试过了,但会导致脚本崩溃。AttributeError: "'builtin_function_or_method' object has no attribute 'new'" - eozzy
1
那么这两个MD5不是同一件事,你可能需要1)重写旧代码,2)使用Python < 2.5,或者3)忽略警告。 - Dyno Fu
1
@3zzy,你有类似于import md5; md5.new(data).hexdigest()的东西,改成from hashlib import md5; md5(data).hexdigest()。虽然是老东西,但我也遇到了同样的错误。 - anttikoo

2

如前所述,可以消除警告。hashlib.md5(my_string)应该与md5.md5(my_string)相同。

>>> import md5
__main__:1: DeprecationWarning: the md5 module is deprecated; use hashlib instead
>>> import hashlib
>>> s = 'abc'
>>> m = md5.new(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
>>> m = hashlib.md5(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72
>>> md5(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'module' object is not callable
>>> md5.md5(s)
<md5 HASH object @ 0x100493260>
>>> m = md5.md5(s)
>>> print s, m.hexdigest()
abc 900150983cd24fb0d6963f7d28e17f72

正如@Dyno Fu所说:你可能需要追踪代码实际从md5调用了什么。


2

那不是错误,而是警告。

如果你仍然坚持想要去除它,那么修改代码,使用hashlib代替。


0

这样的东西怎么样?

try:
    import warnings
    warnings.catch_warnings()
    warnings.simplefilter("ignore")
    import md5
except ImportError as imp_err:
    raise type(imp_err), type(imp_err)("{0}{1}".format(
        imp_err.message,"Custom import message"))

0

我认为这个警告没问题,你仍然可以使用md5模块,或者使用hashlib模块中的md5类。

import hashlib
a=hashlib.md5("foo")
print a.hexdigest()

这将打印字符串 "foo" 的 MD5 校验和


0
请查看文档此处,28.5.3提供了一种抑制弃用警告的方法。或者在运行脚本时,在命令行中输入-W ignore::DeprecationWarning

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接