> 文章列表 > python异常错误怎么看?

python异常错误怎么看?

python异常错误怎么看?

怎么根据异常信息处理异常?

1、从下向上看,先看最后出现的错误的信息是什么(在没有“During  handling  of  the  above  exception, another  exception  occurred:”的情况下),否则直接跳到“During  handling  of  the  above  exception, another  exception  occurred:”之前看错误信息

2、再向上看,直接看出现的错误类型的位置【下面介绍了各种各样的错误类型】ValueError: unsupported pickle protocol: 5(不支持的pickle协议:5

3、根据这个错误类型再进行剖析

一、异常基本原理和信息

def  who_to_greet(person ):return  person  if  person  else  input ('Greet  who? ')def  greet(someone, greeting='Hello'):print(greeting  + ', ' + who_to_greet (someone ))greet (1)

 

 异常信息要从下向上看

最下面的错误是引起这个错误的最后执行行,这个错误的上一个错误是引起最后一个错误的倒数第二个错误。。。。依次向上,最上面的第一个错误就是该错误的入口

剖析上述错误:

  1. 首先,我们需要看的是错误信息的最后一行,通过最后一行可以知道错误的类型以及一些错误原因。
    意思是说:在代码的某个地方,字符串只能和字符串拼接,不能是 int。
  2. 然后我们需要继续向上看,可以看到导致异常的行。然后是文件和行号的代码。看到了第5行出现了错误
  3. 然后继续往上看,第一行执行的代码,我们看到问题代码是 greet()函数调用时传入了一个整数,从而引发了第二个错误【将整数和字符串连接在一起了】

二、During  handling  of  the  above  exception, another  exception  occurred:

def  who_to_greet(person ):return  person  if  person  else  input ('Greet  who? ')def  greet(someone, greeting='Hello'):print(greeting  + ', ' + who_to_greet (someone ))def  greet_many(people):for  person  in  people:# greet(person)try:greet(person )except  Exception:print ('hi, ' + person )greet_many (['Chad', 'Dan', 1])

出现了下面的错误:

Hello, Chad 
Hello, Dan 
Traceback  (most  recent  call  last ):File  "/Users/chenxiangan/pythonproject/demo/greetings.py", line  12, in  greet_many greet (person )File  "/Users/chenxiangan/pythonproject/demo/greetings.py", line  6, in  greet print (greeting  + ', ' + who_to_greet (someone ))
TypeError: can  only  concatenate  str  (not  "int") to  str During  handling  of  the  above  exception, another  exception  occurred:Traceback  (most  recent  call  last ):File  "/Users/chenxiangan/pythonproject/demo/greetings.py", line  17, in  <module>greet_many (['Chad', 'Dan', 1])File  "/Users/chenxiangan/pythonproject/demo/greetings.py", line  14, in  greet_many print ('hi, ' + person )
TypeError: can  only  concatenate  str  (not  "int") to  str 

emmmmm,这次好像不太一样,比之前的内容多了不少,而且有两个 Traceback 块信息,这是什么意思呢? 注意这句话

During  handling  of  the  above  exception, another  exception  occurred:

它的意思是:在处理上述异常期间,发生了另一个异常:简单理解就是 执行try中的代码出现错误,然后执行except 中的代码,在执行except中的代码的时候又出现了异常。所以导致了这种现象。

这种情况怎么看错误信息?

这种情况如果你想调试并修改except中的代码就直接看“During  handling  of  the  above  exception, another  exception  occurred:”之后的错误信息

如果你想调试的是try中的代码,那么就直接看“During  handling  of  the  above  exception, another  exception  occurred:”之前的错误信息【一般都是直接看这个之前的错误信息

三、Python 中有哪些常见的异常类型

1、AttributeError

当你访问一个对象的属性,但是这个属性并没有在这个对象定义的时候,就会引发 AttributeError。

示例1:

下面是一个引发 AttributeError 异常的示例:

a  = 1
a.b 

运行之后引发异常

Traceback  (most  recent  call  last ):File  "/Users/chenxiangan/pythonproject/demo/exmpale.py", line  2, in  <module>a.b 
AttributeError: 'int' object  has  no  attribute  'b'

AttributeError 的错误消息行告诉我们特定对象类型(在本例中为 int)没有访问的属性,在这个例子中没有属性 b。

示例2:

大多数情况下,引发这个异常表明你正在处理的对象可能不是你期望的类型

a_list  = (1, 2)
a_list.append (3)

运行之后抛出异常信息

Traceback  (most  recent  call  last ):File  "/Users/chenxiangan/pythonproject/demo/exmpale.py", line  2, in  <module>a_list.append (3)
AttributeError: 'tuple' object  has  no  attribute  'append'

这里尝试给 a_list 对象进行 append 操作但是引发了异常,

这里的错误信息说,tuple 对象没有 append 属性。

原因就是以为 a_list 是列表但是实际上它是元组,元组是不可变类型不支持添加元素操作所以出错了。这里也告诉大家,以后定义变量名的时候也要主要规范问题,否则就容易出现这种,期望类型错误的情况。

示例3:

还有一种情况就是当对 None 进行属性操作的时候,很容易引发上面的异常

a_list  = None 
a_list.append (3)

运行抛出异常

Traceback  (most  recent  call  last ):File  "/Users/chenxiangan/pythonproject/demo/exmpale.py", line  2, in  <module>a_list.append (3)
AttributeError: 'NoneType' object  has  no  attribute  'append'

是不是很眼熟啊,遇到这种情况不要慌,分析看看你的哪个对象是 None 就好了。

2、ImportError

在使用 import 导入模块时,如果要导入的模块找不到,或者从模块中导入模块中不存在的内容。这时就会触发 ImportError 类型的错误或者它的子类 ModuleNotFoundError。

示例1:

import  aaa 

运行后输出

Traceback  (most  recent  call  last ):File  "/Users/chenxiangan/pythonproject/demo/exmpale.py", line  1, in  <module>import  aaa 
ModuleNotFoundError: No  module  named  'aaa'

在这个例子中可以看到,当我们使用 import 导入一个不存在的模块时,就会出现 ModuleNotFoundError 的错误,Traceback 最下面一句信息给出了原因,没有名为 aaa 的模块.

这时候一般直接下面的操作就行了:

pip install aaa

示例2:

然后我们再运行一个例子

from  collections  import  asdf 

运行之后的内容

Traceback  (most  recent  call  last ):File  "/Users/chenxiangan/pythonproject/demo/exmpale.py", line  1, in  <module>from  collections  import  asdf 
ImportError: cannot  import  name  'asdf' from  'collections'

根据前面的经验我们可以得知原因,不能从 collections 模块中导入名为 asdf 的模块。

有时候为了程序能兼容在各个系统的时候,如果一个包找不到,找另一个的时候,比如在 windows 中不能使用 ujson ,uvloop这两个包,但是在 unix 系统上是可以运行的,这个时候我们就可以使用下面的方法。

try:import  ujson  as  json 
except  ImportError  as  e:import  json 

首先导入 ujson 然后使用 as 给他重命名为 json,如果出现错误就会进入 except 模块

然后导入标准库的 json 包,因为这边的库名已经叫 json 了所以不用再重命名了。记住这个技巧非常的有用哦。

3、IndexError

当你尝试从序列(如列表或元组)中检索索引,但是序列中找不到该索引。此时就会引发 IndexError。

例如

a_list  = ['a', 'b']
a_list[3]

运行之后的结果

Traceback  (most  recent  call  last ):File  "/Users/chenxiangan/pythonproject/demo/exmpale.py", line  2, in  <module>a_list[3]
IndexError: list  index  out  of  range 

通过 IndexError 的错误消息的最后一不能得到一个准确的信息,只知道一个超出范围的序列引用以及序列的类型,在本例中是一个列表。我们需要往上阅读错误信息,才能确定错误的具体位置。这里我们得知错误代码是 a_list[3]原因是索引3 超出了列表的范围,因为最大就是1(索引下标从0 开始的)。

4、KeyError

与 IndexError 类似,当你访问映射(通常是 dict )中不包含的键时,就会引发 KeyError。

a_dict={}
a_dict['b']

运行之后

Traceback  (most  recent  call  last ):File  "/Users/chenxiangan/pythonproject/demo/exmpale.py", line  2, in  <module>a_dict['b']
KeyError: 'b'

KeyError 的错误消息行给出找不到关键字 b。并没有太多的内容,但是,结合上面的错误信息,就可以解决这个问题。

5、NameError

当你引用了变量、模块、类、函数或代码中没有定义的其他名称时,将引发 NameError。一般在拼写变量名出现问题时会引发这种错误。

def  greet (person ):print (f'Hello, {persn}')
greet ('World')

运行之后

Traceback  (most  recent  call  last ):File  "/Users/chenxiangan/pythonproject/demo/exmpale.py", line  3, in  <module>greet ('World')File  "/Users/chenxiangan/pythonproject/demo/exmpale.py", line  2, in  greet print (f'Hello, {persn}')
NameError: name  'persn' is  not  defined 

NameError traceback 的错误消息行给出了缺失的名称 persn。

这个例子中,在 print 使用了没有定义过的变量 persn 所以出现了错误。

6、SyntaxError

当代码中有不正确的 Python 语法时,就会引发 SyntaxError。

下面的问题是函数定义行末尾缺少一个冒号。

def  greet (person )

运行之后

  File  "/Users/chenxiangan/pythonproject/demo/exmpale.py", line  1def  greet (person )^
SyntaxError: invalid  syntax 

SyntaxError 的错误消息行只告诉你代码的语法有问题。查看上面的行才能得到问题所在的行,通常会用一个^(插入符号)指向问题点。

此外,细心的朋友会注意到,在 SyntaxError 异常内容的第一行没有了之前的(most recent call last )。

这是因为 SyntaxError 是在 Python 尝试解析代码时引发的,实际上代码并没有执行。

7、TypeError

当你的代码试图对一个无法执行此操作的对象执行某些操作时,例如将字符串添加到整数中,

以下是引发 TypeError 的几个示例:

>>> 1 + '1'
Traceback  (most  recent  call  last ):File  "<stdin>", line  1, in  <module>
TypeError: unsupported  operand  type (s ) for  +: 'int' and  'str'
>>> '1' + 1
Traceback  (most  recent  call  last ):File  "<stdin>", line  1, in  <module>
TypeError: must  be  str, not  int 
>>> len (1)
Traceback  (most  recent  call  last ):File  "<stdin>", line  1, in  <module>
TypeError: object  of  type  'int' has  no  len ()

以上所有引发类型错误的示例都会产生包含不同消息的错误消息行。它们每一个都能很好地告诉你哪里出了问题。

前两个示例尝试将字符串和整数相加。然而,它们有细微的不同

  • 第一个是尝试在 int 中拼接一个 str。
  • 第二个是尝试在 str 中拼接一个 int。

错误消息行反映了这些差异。

最后一个示例尝试在 int 上调用 len ()。

错误消息行告诉我们不能使用 int 执行此操作。

8、ValueError

当对象的值不正确时就会引发 ValueError。这个和我们前面说的因为索引的值不在序列的范围内,而导致 IndexError 异常类似。

>>> a, b, c  = [1, 2]
Traceback  (most  recent  call  last ):File  "<stdin>", line  1, in  <module>
ValueError: not  enough  values  to  unpack  (expected  3, got  2)
>>> a, b  = [1, 2, 3]
Traceback  (most  recent  call  last ):File  "<stdin>", line  1, in  <module>
ValueError: too  many  values  to  unpack  (expected  2)

这些示例中的 ValueError 错误消息行可以准确地告诉我们值的一些问题:

在第一个示例中,错误信息行是没有足够多的值去 unpack (解包)。括号理面详细的写了你希望解包3个值但实际上只给了2 个。

第二个示例中,错误信息行是解包太多的值。先解包3 个值但是只给了2 个变量,所以括号里提示 expected 2 就是说期望的实际是解包2 个值。

一个实际的例子:

2023-04-14 21:38:51 | INFO | unicore.tasks.unicore_task | get EpochBatchIterator for epoch 1
Traceback (most recent call last):File "/home/mapengsen/anaconda3/envs/unimol37/bin/unicore-train", line 8, in <module>sys.exit(cli_main())File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore_cli/train.py", line 403, in cli_maindistributed_utils.call_main(args, main)File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/distributed/utils.py", line 190, in call_maindistributed_main(args.device_id, main, args, kwargs)File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/distributed/utils.py", line 164, in distributed_mainmain(args, **kwargs)File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore_cli/train.py", line 110, in maindisable_iterator_cache=False,File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/checkpoint_utils.py", line 236, in load_checkpointepoch=1, load_dataset=True, **passthrough_argsFile "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/trainer.py", line 524, in get_train_iteratorself.reset_dummy_batch(batch_iterator.first_batch)File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/data/iterators.py", line 243, in first_batchreturn self.collate_fn([self.dataset[i] for i in self.frozen_batches[0]])File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/data/iterators.py", line 243, in <listcomp>return self.collate_fn([self.dataset[i] for i in self.frozen_batches[0]])File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/data/base_wrapper_dataset.py", line 18, in __getitem__return self.dataset[index]File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/data/nested_dictionary_dataset.py", line 69, in __getitem__return OrderedDict((k, ds[index]) for k, ds in self.defn.items())File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/data/nested_dictionary_dataset.py", line 69, in <genexpr>return OrderedDict((k, ds[index]) for k, ds in self.defn.items())File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/data/base_wrapper_dataset.py", line 18, in __getitem__return self.dataset[index]File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/data/append_token_dataset.py", line 21, in __getitem__item = self.dataset[idx]File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/data/prepend_token_dataset.py", line 22, in __getitem__item = self.dataset[idx]File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/data/tokenize_dataset.py", line 26, in __getitem__raw_data = self.dataset[index]File "/mnt/d/Pycharm_workspace/KD/Uni-Mol/unimol/unimol/data/key_dataset.py", line 19, in __getitem__return self.dataset[idx][self.key]File "/mnt/d/Pycharm_workspace/KD/Uni-Mol/unimol/unimol/data/normalize_dataset.py", line 32, in __getitem__return self.__cached_item__(index, self.epoch)File "/mnt/d/Pycharm_workspace/KD/Uni-Mol/unimol/unimol/data/normalize_dataset.py", line 23, in __cached_item__dd = self.dataset[index].copy()File "/mnt/d/Pycharm_workspace/KD/Uni-Mol/unimol/unimol/data/cropping_dataset.py", line 42, in __getitem__return self.__cached_item__(index, self.epoch)File "/mnt/d/Pycharm_workspace/KD/Uni-Mol/unimol/unimol/data/cropping_dataset.py", line 29, in __cached_item__dd = self.dataset[index].copy()File "/mnt/d/Pycharm_workspace/KD/Uni-Mol/unimol/unimol/data/remove_hydrogen_dataset.py", line 55, in __getitem__return self.__cached_item__(index, self.epoch)File "/mnt/d/Pycharm_workspace/KD/Uni-Mol/unimol/unimol/data/remove_hydrogen_dataset.py", line 32, in __cached_item__dd = self.dataset[index].copy()File "/mnt/d/Pycharm_workspace/KD/Uni-Mol/unimol/unimol/data/atom_type_dataset.py", line 25, in __getitem__if len(self.dataset[index]["atoms"]) != len(self.dataset[index]["coordinates"]):File "/mnt/d/Pycharm_workspace/KD/Uni-Mol/unimol/unimol/data/conformer_sample_dataset.py", line 34, in __getitem__return self.__cached_item__(index, self.epoch)File "/mnt/d/Pycharm_workspace/KD/Uni-Mol/unimol/unimol/data/conformer_sample_dataset.py", line 25, in __cached_item__atoms = np.array(self.dataset[index][self.atoms])File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/unicore/data/lmdb_dataset.py", line 49, in __getitem__data = pickle.loads(datapoint_pickled)
ValueError: unsupported pickle protocol: 5
ERROR:torch.distributed.elastic.multiprocessing.api:failed (exitcode: 1) local_rank: 0 (pid: 2145) of binary: /home/mapengsen/anaconda3/envs/unimol37/bin/pythonreturn launch_agent(self._config, self._entrypoint, list(args))File "/home/mapengsen/anaconda3/envs/unimol37/lib/python3.7/site-packages/torch/distributed/launcher/api.py", line 248, in launch_agentfailures=result.failures,
torch.distributed.elastic.multiprocessing.errors.ChildFailedError:

1、从下向上看:最后的错误说分布式的多进程中的一个子进程出现了错误

2、向上看,直接看出现的错误类型的位置:ValueError: unsupported pickle protocol: 5(不支持的pickle协议:5),由此推断是pickle包的版本安装错误相关的原因

3、查找百度:

4、问题解决

一文教你读懂 Python 中的异常信息!这改bug就容易了吗? - 知乎