0%

python报错整理

python日常程序中遇到报错很多,开个帖子记录一下

ascii codec can’t decode

‘ascii’ codec can’t decode byte 0xe7 in position 0: ordinal not in range(128)
Python的str默认是ascii编码,和unicode编码冲突.
解决方法:
在代码头部添加

1
2
3
import sys
reload(sys)
sys.setdefaultencoding('utf8')

No module named XXX

一般这个问题有两种可能一种是引用的外部依赖 需要自己安装下

1
pip install XXX

第二种是自己引用自己的 代码,需要在被引用代码的同级创建 init.py空白就行

NameError变量名错误

报错

1
2
3
4
>>> print a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

解决方案:

先要给a赋值。才能使用它。在实际编写代码过程中,报NameError错误时,查看该变量是否赋值,或者是否有大小写不一致错误,或者说不小心将变量名写错了。

注:在Python中,无需显示变量声明语句,变量在第一次被赋值时自动声明。

IndentationError代码缩进错误

1
IndentationError: expected an indented block

缩进有误,python的缩进非常严格,行首多个空格,少个空格都会报错。这是新手常犯的一个错误,由于不熟悉python编码规则。像def,class,if,for,while等代码块都需要缩进。

缩进为四个空格宽度,需要说明一点,不同的文本编辑器中制表符(tab键)代表的空格宽度不一,如果代码需要跨平台或跨编辑器读写,建议不要使用制表符。

invalid syntax

一般是成对的符号(如括号)未成对使用的情况
还有可能是缩进问题 一般是这两种情况

AttributeError对象属性错误

‘module’ object has no attribute ‘Path’
python对大小写敏感 有可能是大小写问题 也可能是没有这个方法
可以用dir函数查看某个模块的属性

入参个数错误

报错 takes exactly 2 arguments (3 given)
两个参数的函数 传递了3个参数
查看某个函数的使用,可以使用help查看

object is not callable

非函数却以函数来调用

IOError输入输出错误

文件不存在报错
1
2
3
4
>>> f=open("Hello.py")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'Hello.py'

open()函数没有指明mode,默认为只读方式,如果该目录下没有Hello.py的文件,则会报错,可查看是否拼写有错误,或者是否大小写错误,或者根本不存在这个文件
python知识拓展:

如何查看python解释器当前路径:

1
2
>>> import os
>>> os.getcwd()
因文件权限问题报错
1
2
3
4
5
>>> f=open("hello.py")
>>> f.write("test")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: File not open for writing

open(“hello.py”)如果入参没有加读写模式参数mode,说明默认打开文件的方式为只读方式,而此时又要写入字符,所以权限受限,才会报错。

解决方案:

更改模式

1
2
>>> f=open("hello.py",'w+')
>>> f.write("test")

KeyError字典键值错误

测试一接口,接口返回数据一般是json格式,而测试该接口校验某个值是否正确,如果key拼写错了,就会报KeyError。简单举例如下:

1
2
3
4
5
6
7
>>> d={'a':1,'b':2,'c':3}
>>> print d['a']
1
>>> print d['f']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'f'

访问了不存在的键值

Non-ASCII character ‘\xe3’ in file saveImg.py on line 7, but no encoding declared

是因为Python在默认状态下不支持源文件中的编码所致。解决方案有如下三种:

一、在文件头部添加如下注释码:

1
# coding=<encoding name> 例如,可添加# coding=utf-8

二、在文件头部添加如下两行注释码:

1
2
3
# !/usr/bin/python

# -*- coding: <encoding name> -*-例如,可添加# -*- coding: utf-8 -*-

三、设置文件编码:

1
2
3
# !/usr/bin/python

可添加# vim "set fileencoding=utf-8"