Python异常处理

Python异常错误

  • 异常类型
  • SyntaxError
    • SyntaxError :invalid syntax
    • SyntaxError: Non-UTF-8 code starting with 'xe5' in file ***.py on line 105, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for
    • SyntaxError: EOL while scanning string literal
    • SyntaxError: invalid syntax
    • SyntaxError:invalid syntax
    • SyntaxError: invalid syntax
    • SyntaxError: Non-UTF- code starting with '\xb6' in file XX.py on line , but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
  • TypeError
    • TypeError: ‘list’ object cannot be interpreted as an integer
    • TypeError: ‘str’ object does not support item assignment
    • TypeError: Can’t convert ‘int’ object to str implicitly
    • TypeError:can only concatenate str (not "int") to str
    • TypeError: ‘range’ object does not support item assignment
    • TypeError: num_money() takes 0 positional arguments but 1 was given
  • IndexError
    • IndexError: list index out of range
  • KeyError
    • KeyError: '100'
  • NameError
    • NameError: name ‘num_money2’ is not defined
    • NameError: name ‘money’ is not defined
  • UnboundLocalError
    • UnboundLocalError: local variable ‘num_money’ referenced before assignment
  • IndentationError
    • IndentationError:unexpected indent
    • IndentationError:unindent does not match any outer indetation level
    • IndentationError:expected an indented block
  • AttributeError
    • AttributeError : 'NoneType' object has no attribute
    • AttributeError: ‘str’ object has no attribute ‘lowerr’
    • AttributeError: 'NoneType' object has no attribute 'tokenize'
    • AttributeError: ‘Line2D‘ object has no property ‘lable‘ 解决:matplotlib中问题
  • ModuleNotFoundError
    • ModuleNotFoundError: No module named 'calc'
    • ModuleNotFoundError: No module named ‘exceptions‘
    • ModuleNotFoundError: No module named 'cv2'
    • ModuleNotFoundError: No module named 'pptx'
    • ModuleNotFoundError: No module named ‘pytorch_pretrained_bert’
  • UnicodeDecodeError
    • UnicodeDecodeError: 'utf-8' codec can't decode byte 0xbe in position 0: invalid start byte
  • ValueError
    • ValueError: unable to parse config.json as a URL or as a local path
  • 其他异常错误
    • 浏览器F12进入调试界面总是停留在Debugger Paused
    • UserWarning: This overload of add_ is deprecated
    • TypeError: addcmul_() got an unexpected keyword argument 'alpha'
    • 运行报错:run.py: error: the following arguments are required: --model
    • ’WebDriver’ object has no attribute ‘find_element_by_xpath’
  • Django
    • django.db.utils.OperationalError: (1049, “Unknown database ‘django‘“)
    • OperationalError: (2005, "Unknown MySQL server host 'localhost' (11001)")

异常类型

Python异常处理_第1张图片

SyntaxError

SyntaxError :invalid syntax

第一种情况:忘记在if,for,def,elif,else,class等声明末尾加“:”
第二种情况:使用 = 而不是 ==

SyntaxError: Non-UTF-8 code starting with ‘xe5’ in file ***.py on line 105, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for

开头添加 # encoding:utf-8

SyntaxError: EOL while scanning string literal

or

SyntaxError: invalid syntax

在字符串首尾忘记加引号
异常代码:

print(I have a lot of money')

num_money = '10000'
print('I have ' + num_money +  yuan')

正确代码:

print('I have a lot of money')

num_money = '10000'
print('I have ' + num_money + ' yuan')

SyntaxError:invalid syntax

尝试使用Python关键字def作为变量名
可用以下代码获取关键字

import keyword
print(keyword.kwlist)  # 获取保留字

异常代码:

def = 'yun'

正确代码:

def1 = 'yun'

SyntaxError: invalid syntax

不存在 ++ 或者 – 自增自减操作符
异常代码:

money = 1
money++

正确代码:

money = 1
money += 1

SyntaxError: Non-UTF- code starting with ‘\xb6’ in file XX.py on line , but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

直接在文件头处加 # encoding:utf-8 就行了,python3.8特色

TypeError

TypeError: ‘list’ object cannot be interpreted as an integer

在 for 循环语句中忘记调用 len()
通常你想要通过索引来迭代一个list或者string的元素,这需要调用 range() 函数。要记得返回len 值而不是返回这个列表
异常代码:

money = ['10', '20', '50']
for i in range(money):
  print(money[i])

正确代码:

money = ['10', '20', '50']
for i in range(len(money)):
  print(money[i])

TypeError: ‘str’ object does not support item assignment

尝试修改string的值,string是一种不可变的数据类型
异常代码:

money = 'I have a lot of money'
money[1] = 'not'
print(money)

正确代码:

money = 'I have a lot of money'
money = money[:0] + 'I not ' + money[1:]
print(money)

TypeError: Can’t convert ‘int’ object to str implicitly

or

TypeError:can only concatenate str (not “int”) to str

尝试连接非字符串值与字符串
异常代码:

num_money = 10
print('I have ' + num_money + ' yuan')

正确代码:

num_money = 10
print('I have ' + str(num_money) + ' yuan')

num_money = 10
print('I have %s yuan' % (num_money))

TypeError: ‘range’ object does not support item assignment

尝试使用 range()创建整数列表
有时你想要得到一个有序的整数列表,所以 range() 看上去是生成此列表的不错方式。然而,你需要记住 range() 返回的是 “range object”,而不是实际的 list 值
异常代码:

money = range(10)
money[4] = -1
print(money)

正确代码:

money = list(range(10))
money[4] = -1
print(money)

TypeError: num_money() takes 0 positional arguments but 1 was given

忘记为方法的第一个参数添加self参数
异常代码:

class money():
  def num_money():
      print('I have a lot of money')
me = money()
me.num_money()

正确代码:

class money():
  def num_money(self):
      print('I have a lot of money')
me = money()
me.num_money()

IndexError

IndexError: list index out of range

引用超过list最大索引
异常代码:

money = ['10', '20', '50']
print(money[6])

正确代码:

money = ['10', '20', '50']
print(money[2])

KeyError

KeyError: ‘100’

使用不存在的字典键值
异常代码:

money = {'10': '一张', '20': '两张', '50': '三张'}
print('I have ' + money['100'] + ' qian')

正确代码:

money = {'10': '一张', '20': '两张', '50': '三张'}
print('I have ' + money['10'] + ' qian')

NameError

NameError: name ‘num_money2’ is not defined

在一个定义新变量中使用增值操作符
异常代码:

num_money1 = 10
num_money += 20
num_money2 += 20

正确代码:

num_money1 = 10
num_money1 += 10
num_money2 = 20
num_money2 += 20

NameError: name ‘money’ is not defined

变量或者函数名拼写错误
异常代码:

money = 'qian'
print('I have a lot of ' + mone)

num_money = rangee(10)

正确代码:

money = 'qian'
print('I have a lot of ' + money)

num_money = range(10)

UnboundLocalError

UnboundLocalError: local variable ‘num_money’ referenced before assignment

在定义局部变量前在函数中使用局部变量(此时有与局部变量同名的全局变量存在),如果在函数中定义了任何东西,如果它只是在函数中使用那它就是局部的,反之就是全局变量
异常代码:

num_money = 10000
def money():
  print(num_money)
  num_money = 100
money()

正确代码:

num_money = 10000
def money():
  print(num_money)
money()

IndentationError

IndentationError:unexpected indent

or

IndentationError:unindent does not match any outer indetation level

or

IndentationError:expected an indented block

错误的使用缩进量导致,记住缩进增加只用在已结束的语句之后,而之后必须恢复到之前的缩进格式
异常代码:

print('I have a lot of money')
  print('I have a lot of money')

正确代码:

print('I have a lot of money')
print('I have a lot of money')

AttributeError

AttributeError : ‘NoneType’ object has no attribute

第一步:NoneType之所以出现是因为定义了一个变量或函数,却没有值或者返回值,因此会默认值为None
第二步:我查到使用的函数设置为没有返回值,然后赋值一个默认值none,导致下一个引用报错

AttributeError: ‘str’ object has no attribute ‘lowerr’

方法名拼写错误
异常代码:

money = 'I have a lot of money'
money = money.lowerr()

正确代码:

money = 'I have a lot of money'
money = money.lower()     # lower错误

AttributeError: ‘NoneType’ object has no attribute ‘tokenize’

有可能缺失vocab.txt,或者vocab.txt数据缺失,因为tokenizer的加载是需要vocab.txt的,可以将原始下载的预训练模型目录中的vocab.txt copy一份或者网上下载一份即可

AttributeError: ‘Line2D‘ object has no property ‘lable‘ 解决:matplotlib中问题

仔细反省,是label,不是lable。出错就是写错了,没有其他的错误的可能,又是粗心的后果

plt.axvline(minposs, linestyle='--', color = 'r', label='Early Stopping Checkpoint')
plt.xlabel('epochs')

ModuleNotFoundError

ModuleNotFoundError: No module named ‘calc’

模块不存在,或者模块名拼写错误
异常代码:

import calc

ModuleNotFoundError: No module named ‘exceptions‘

需要卸载docx模块

pip uninstall docx

重新安装python-docx模块即可解决问题

pip install python-docx

ModuleNotFoundError: No module named ‘cv2’

pip install opencv-python   # 如果只用主模块,使用这个命令安装
pip install opencv-contrib-python # 如果需要用主模块和contrib模块,使用这个命令安装

ModuleNotFoundError: No module named ‘pptx’

需要卸载pptx模块

pip uninstall pptx

重新安装python-pptx模块即可解决问题

pip install python-pptx

ModuleNotFoundError: No module named ‘pytorch_pretrained_bert’

进入pycharm的终端,激活环境

conda activate python

pycharm终端安装pytorch_pretrained_bert

pip install pytorch_pretrained_bert==0.6.1 -i https://pypi.tuna.tsinghua.edu.cn/simple

Python异常处理_第2张图片

UnicodeDecodeError

UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xbe in position 0: invalid start byte

f = open('1.txt', 'r', encoding='utf-8')

方法1、将 encoding=’utf-8’ 中‘utf-8‘改为GB2312、gbk、ISO-8859-1

方法2、f = open(‘1.txt’,encoding=‘gbk’)

ValueError

ValueError: unable to parse config.json as a URL or as a local path

有可能文件路径只有bert_config.json文件没有config.json文件,那么要么更改from_pretrained方法的源代码,要么更改文件名称。建议更改文件名称尝试一下

其他异常错误

浏览器F12进入调试界面总是停留在Debugger Paused

在这里插入图片描述
解决办法:
点击标注的停用断点,有时候需要放大才能找到
Python异常处理_第3张图片
点击之后,重新调试,问题解决
在这里插入图片描述

UserWarning: This overload of add_ is deprecated

UserWarning: This overload of add_ is deprecated: add_(Number alpha, Tensor other) Consider using one of the following signatures instead: add_(Tensor other, *, Number alpha)

UserWarning: This overload of addcmul_ is deprecated: addcmul_(Number value, Tensor tensor1, Tensor tensor2) Consider using one of the following signatures instead:addcmul_(Tensor tensor1, Tensor tensor2, *, Number value)

两个警告,不影响代码运行 PyTorch版本问题
解决方法

# 改之前
next_m.mul_(beta1).add_(1 - beta1, grad)
next_v.mul_(beta2).addcmul_(1 - beta2, grad, grad)

# 改之后
next_m.mul_(beta1).add_(grad, alpha=1 - beta1)
next_v.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)

后面如果出现

TypeError: addcmul_() got an unexpected keyword argument ‘alpha’

改之后 第一行后面为alpha 第二行为value
不然会报错

# 改之后
next_m.mul_(beta1).add_(grad, alpha=1 - beta1)
next_v.mul_(beta2).addcmul_(grad, grad, value=1 - beta2)

运行报错:run.py: error: the following arguments are required: --model

缺少配置参数
Pycharm的编辑设置,加上–model–model=****
Python异常处理_第4张图片
我需要运行的模型为bert,因此为l–model=bert,添加之后确定即可
在这里插入图片描述

’WebDriver’ object has no attribute ‘find_element_by_xpath’

因为Selenium4.x的版本,已经弃用了find_element_by_xpath这样的写法,就会报错
解决方法:

find_element_by_id(‘路径’)
find_element_by_xpath(‘路径’)
find_elements_by_class_name(‘路径’)
# 把结尾的元素改写成下面的格式
find_element(By.ID, ‘路径’)
find_element(By.XPATH, ‘路径’)
find_element(By.CLASS_NAME, ‘路径’)

Django

django.db.utils.OperationalError: (1049, “Unknown database ‘django‘“)

字面意思,没有找到django这个数据库
解决方法:mysql中新建一个django数据库
之后运行 python manage.py migrate

OperationalError: (2005, “Unknown MySQL server host ‘localhost’ (11001)”)

根据提示信息判断是说mysql server 无法识别 localhost
打开 setting.py 文件,修改 DATABASES 中的HOST的值为数据库的ip地址即可

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'django',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': 'localhost' , # 把localhost 改为 127.0.0.1
        'PORT': '3306',
    }
}

一部分参考自:https://blog.csdn.net/libaiup/article/details/122664530?spm=1001.2014.3001.5501

你可能感兴趣的:(python,开发语言)