Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
2016-11-21 12:58
1171 查看
Python脚本执行总报错"AttributeError: 'module' object has no attribute'xxx'"。
问题定位:
查看import库的源文件,发现源文件存在且没有错误,同时存在源文件的.pyc文件
问题解决方法:
1. 命名py脚本时,不要与python预留字,模块名等相同(这一点非常重要哦!看看你有没有一个文件的名字有问题的)
2. 删除该库的.pyc文件(因为py脚本每次运行时均会生成.pyc文件;在已经生成.pyc文件的情况下,若代码不更新,运行时依旧会走pyc,所以要删除.pyc文件),重新运行代码;或者找一个可以运行代码的环境,拷贝替换当前机器的.pyc文件即可
示例:
如下Python代码,执行时报错"AttributeError: 'module' object has no attribute 'urlopen'",更新Python27\Lib\urllib2.pyc文件后,即可正常运行。
附录:
pyc文件介绍
pyc文件,是python编译后的字节码(bytecode)文件。只要你运行了py文件,python编译器就会自动生成一个对应的pyc字节码文件。这个pyc字节码文件,经过python解释器,会生成机器码运行(这也是为什么pyc文件可以跨平台部署,类似于java的跨平台,java中JVM运行的字节码文件)。下次调用直接调用pyc,而不调用py文件。直到你这个py文件有改变。python解释器会检查pyc文件中的生成时间,对比py文件的修改时间,如果py更新,那么就生成新的pyc。
问题定位:
查看import库的源文件,发现源文件存在且没有错误,同时存在源文件的.pyc文件
问题解决方法:
1. 命名py脚本时,不要与python预留字,模块名等相同(这一点非常重要哦!看看你有没有一个文件的名字有问题的)
2. 删除该库的.pyc文件(因为py脚本每次运行时均会生成.pyc文件;在已经生成.pyc文件的情况下,若代码不更新,运行时依旧会走pyc,所以要删除.pyc文件),重新运行代码;或者找一个可以运行代码的环境,拷贝替换当前机器的.pyc文件即可
示例:
如下Python代码,执行时报错"AttributeError: 'module' object has no attribute 'urlopen'",更新Python27\Lib\urllib2.pyc文件后,即可正常运行。
import urllib2 url = "http://www.baidu.com" f = urllib2.urlopen(url, timeout=5).read() print len(f)
附录:
pyc文件介绍
pyc文件,是python编译后的字节码(bytecode)文件。只要你运行了py文件,python编译器就会自动生成一个对应的pyc字节码文件。这个pyc字节码文件,经过python解释器,会生成机器码运行(这也是为什么pyc文件可以跨平台部署,类似于java的跨平台,java中JVM运行的字节码文件)。下次调用直接调用pyc,而不调用py文件。直到你这个py文件有改变。python解释器会检查pyc文件中的生成时间,对比py文件的修改时间,如果py更新,那么就生成新的pyc。
相关文章推荐
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- 【Python 脚本报错】AttributeError:'module' has no attribute 'xxx'的解决方法
- 【python学习笔记(2)】脚本报错"AttributeError: 'module' object has no attribute 'xxx'"解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’
- python错误:AttributeError: 'module' object has no attribute 'setdefaultencoding'问题的解决方法
- python错误:AttributeError: 'module' object has no attribute 'setdefaultencoding'问题的解决方法
- Python脚本报错AttributeError: ‘module’ object has no attribute ’urllibopen'(Python 2.7.11 )
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- 解决Python报错: AttributeError: 'module' object has no attribute '_base'
- Python脚本报错AttributeError: ‘module’ object has no attribute’xxx’解决方法
- Python3.X识别混合编码,顺便解决“AttributeError: 'module' object has no attribute 'urlopen'”