【问题标题】:How to print the exception string in <class> for Python [duplicate]如何在 Python 的 <class> 中打印异常字符串 [重复]
【发布时间】:2020-11-14 12:14:38
【问题描述】:

我在 Windows 10 上使用 Python 3.8.3。我有以下代码:

import # all the necessary modules

try:
    # do something
except WebDriverException:
    print(sys.exc_info()[0])

出现异常时,我收到以下信息:

<class 'selenium.common.exceptions.SessionNotCreatedException'>

如何让print() 只输出&lt;class&gt; 中的字符串?:

selenium.common.exceptions.SessionNotCreatedException

任何帮助将不胜感激。

【问题讨论】:

  • except WebDriverException as exc: print(type(exc))?
  • @jonrsharpe 打印出的内容与print(sys.exc_info()[0]) 完全相同。我只想在 . 之后输出字符串
  • @jonrsharpe 我也试过了。下面的第一个答案是用__name__ 修改的,但它只给出SessionNotCreatedException。哪个很接近,但不是确切的字符串。
  • 然后参见例如stackoverflow.com/q/2020014/3001761 - 这里的context是什么,你用它做什么,你已经做了什么研究?

标签: python python-3.x windows


【解决方案1】:

要获取异常的完整路径,请使用 inspect.getmodule 方法获取包名并使用 type(..).__name __ 获取类名。

except WebDriverException as ex: 
    print (type(ex).__name__)

全名试试

import inspect
.....
print(inspect.getmodule(ex).__name__, type(ex).__name__, sep='.')

为简单起见,您只需解析已有的字符串

print(str(sys.exc_info()[0])[8:-2]) # selenium.common.exceptions.SessionNotCreatedException

【讨论】:

  • 我试过了。它不打印字符串。相反,它会打印 sys.exc_info()[1] 将输出的相同内容。
  • 答案已更新:type(ex).__name__
  • 这更接近了。它打印SessionNotCreatedException。虽然希望完整的字符串。谢谢。
  • 谢谢。 inspect 模块使用完美。
  • 为什么不type(ex).__module__
【解决方案2】:

也许你可以试试这个

import # anything

try:
   # something
except Exception as e:
   print(e)

【讨论】:

  • 我从第一个答案中尝试了这个。正如我在那里评论的那样,这会产生与sys.exc_info()[1] 相同的输出,而不是我在我的问题中寻找的字符串。
猜你喜欢
  • 2014-01-02
  • 1970-01-01
  • 1970-01-01
  • 2020-02-09
  • 2012-10-04
  • 2017-04-05
  • 2014-09-25
  • 2020-10-27
  • 2018-05-09
相关资源
最近更新 更多