【问题标题】:python error "AttributeError: 'module' object has no attribute 'sha1'"python错误“AttributeError:'module'对象没有属性'sha1'”
【发布时间】:2014-04-03 16:46:00
【问题描述】:

我需要你的帮助,

如何纠正错误 AttributeError: 'module' object has no attribute 'sha1',

当我启动命令示例 import random 或 import hashlib 我得到这样的结果

root@thinkad:~# python
Python 2.7.3 (default, Jan  2 2013, 13:56:14) 
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/random.py", line 49, in <module>
    import hashlib as _hashlib
  File "hashlib.py", line 3, in <module>
    hasher = hashlib.sha1()
AttributeError: 'module' object has no attribute 'sha1'
>>> import math
>>> import hashlib
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "hashlib.py", line 3, in <module>
    hasher = hashlib.sha1()
AttributeError: 'module' object has no attribute 'sha1'
>>> 

【问题讨论】:

  • 您能否运行import hashlib; print dir(hashlib), hashlib.__file__ 并将输出包含在问题中。
  • 相同的 AttributeError: 'module' 对象没有属性 'sha1'

标签: linux python-2.7 hashlib


【解决方案1】:

在安装了一些 brew cask 之后出现了问题,该 brew cask 之后进行了一些定期清理。然后 node-gyp 无法为我的节点应用程序重建一些包。重新安装 python 2 帮助了我。

在 macOS 上:

brew reinstall python@2

【讨论】:

  • 更新 python 2 解决了我的问题,但似乎 python@2 已从自制软件中删除。你仍然可以像this other thread一样重新安装它。
【解决方案2】:

错误原因

当您在执行脚本的位置在同一目录中有一个文件时(或者即使它是正在运行的脚本本身)与内置模块命名相同 strong>,它被加载而不是内置模块。

修复

要修复它,您只需将文件 hashlib.py 重命名为其他名称,然后 Python 解释器将加载内置模块。您可能还需要删除与您的hashlib.py 位于同一目录中的已编译模块hashlib.pyc,否则Python 仍将加载该模块。

说明

当你import 一个模块时,比如说import hashlib,Python 在following locations and in the following order 中寻找模块hashlib.py:

  1. 包含正在运行的脚本的目录
  2. 内置模块
  3. 包含输入脚本的目录(或未指定文件时的当前目录)
  4. PYTHONPATH 环境变量(可能包含目录列表)
  5. 依赖于安装的默认路径

这意味着如果您执行包含语句import hashlib 的脚本hashlib.py,Python 会导入脚本本身而不是内置模块hashlib。事实上,Python 将您的脚本编译到同一目录中的文件 hashlib.pyc 中并导入该编译后的脚本,因此如果您只是重命名 hashlib.py 并将 haslib.pyc 保留在原处,它仍然会加载它。因此您还需要删除haslib.pyc。

【讨论】:

    【解决方案3】:

    在更新一个包后,我在 anaconda 环境中遇到了同样的错误,该包也引入了一个新的 python 版本。在我的情况下,conda remove python 后跟 conda install python=2.7 修复了这个问题。

    【讨论】:

      【解决方案4】:

      您似乎有一个名为 hashlib.py 的文件,它妨碍了解释器查找标准 hashlib 模块。

      【讨论】:

      • 是的,兄弟 :D 谢谢,但我该怎么做?我删除这些文件?
      • @PyDroid 你为什么要删除那个文件?没有任何意义。这是你的源代码。只需重命名它就不会再与haslib 模块发生冲突。
      • 感谢帮助我将文件命名为 hashlib.py :) 哎呀。感谢您的帮助
      猜你喜欢
      • 2018-06-14
      • 2015-05-19
      • 2021-01-15
      • 2015-05-16
      • 1970-01-01
      • 2022-12-20
      • 2023-03-22
      • 2016-01-18
      • 1970-01-01
      相关资源
      最近更新 更多