首页 > 解决方案 > Python 2 与 Python 3 中的 sys.exc_info()

问题描述

我在 Python 3 中处理异常时遇到了一些困难。在 Python 2.7 和 3.8 中,我都有这个片段让您了解我如何处理错误/异常:

## 
def tearDown(self):
  type_except, value, traceback = sys.exc_info()
  print("This is the exception type:", type_except)
  if not type_except:
    self.info("This was successful")
  elif type_except is self.failureException:
    self.warning(self.failure_message(type_except, value, tb))
    self.info("This failed")
  else:
    self.error(self.error_message(type_except, value, tb))
    self.info("This resulted in an ERROR")

在 Python 2 中,一切都按预期工作,当我遇到异常时,我会收到错误消息,当我打印什么type_except是:

这是异常类型:

<type 'exceptions.AssertionError'>

在 Python 3 中,当运行相同的测试时,由于相同的原因而失败,我得到一个Nones的元组sys.exc_info()。因此,我失败的测试通过了。

蟒蛇 3:

This is the exception type: None

有谁知道为什么会发生这种情况?我查看sys.exc_info()了 2.7 和 3.8 的定义,但它们看起来是一样的。

--

更多信息: 测试如下:

def test1_simpleLoad(self):
        '''Perform a simple load from a xxx server'''
        try:
            # Create session, connects to websocket, loads a wordset
            # Load wordset
            #compares expected response 
        finally:
            self._websocket.cleanup()

在每次测试结束时,都会调用 tearDown 类,也就是上面提供的代码 ^

标签: pythonpython-3.xtestingexception

解决方案


推荐阅读