Skip to main content
 首页 » 编程设计

Python2 "raise e[0], e[1], e[2]"和 python3 版本在一个文件中

2024年11月01日11langtianya

我发现 python 3 相当于:

raise e[0], e[1], e[2] 

看起来像这样:

raise e[0](e[1]).with_traceback(e[2]) 

但是我得到第一个语法错误(在 python 3 中)或 object has no attribute 'with_traceback'(在 python 2 中)

如何在没有错误的情况下为两个版本编写这些行?

请您参考如下方法:

好像six.reraise就是您所追求的。

使用在 py2 和 py3 中均有效的不同回溯引发异常的示例:

from __future__ import print_function 
import sys 
import six 
 
 
def this_should_show_up_in_the_traceback(): 
    raise ValueError("an exception") 
 
try: 
    this_should_show_up_in_the_traceback() 
except: 
    type, value, tb = sys.exc_info() 
 
print('stashed a traceback for later', type, value, tb) 
 
six.reraise(IndexError, IndexError("other exception"), tb)