【问题标题】:How to determine correct exception class如何确定正确的异常类
【发布时间】:2020-09-19 01:53:13
【问题描述】:

我正在使用 Python WMI 模块从 Windows 系统收集硬件信息。这行引发了一个异常:

numa = c.Win32_PerfFormattedData_PerfOS_NUMANodeMemory()
Traceback (most recent call last):
  File "wmi.py", line 1209, in __getattr__
  File "wmi.py", line 1220, in _cached_classes
  File "<COMObject winmgmts:>", line 3, in Get
  File "win32com\client\dynamic.py", line 287, in _ApplyTypes_
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'SWbemServicesEx', None, None, 0, -1073738817), None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "health_check.py", line 1138, in <module>
  File "health_check.py", line 1121, in main
  File "health_check.py", line 228, in hardware_info
  File "wmi.py", line 1211, in __getattr__
  File "win32com\client\dynamic.py", line 527, in __getattr__
AttributeError: winmgmts:.Win32_PerfFormattedData_PerfOS_NUMANodeMemory

所以我试着像这样抓住它:

import pywintypes.com_error
try:
    numa = c.Win32_PerfFormattedData_PerfOS_NUMANodeMemory()

except pywintypes.com_error:
    logger.error('Failed to read NUMA status.')

但是导入失败:

Traceback (most recent call last):
  File "health_check.py", line 20, in <module>
ModuleNotFoundError: No module named 'pywintypes.com_error'; 'pywintypes' is not a package
[9464] Failed to execute script health_check

我尝试不导入com_error 类,但这也不起作用。如何找到正确的导入来捕获此类异常?导入wmi 后,模块存在于此处:

>>> sys.modules['pywintypes']
<module 'pywintypes' (C:\WINDOWS\SYSTEM32\pywintypes37.dll)>
>>> sys.modules['pywintypes'].com_error
<class 'pywintypes.com_error'>

【问题讨论】:

  • 这与使用正确或不正确的异常类无关。导入模块:import pywintypes。您不能在 import thing.whatever 中指定非模块。
  • 这能回答你的问题吗? How to catch these exceptions individually?
  • 我试过了;它没有捕获异常
  • @fooiey 非常有帮助,谢谢! BaseException 有效。但我的问题的核心是,给定一个新的(可能是未记录的)模块,你怎么能解决这个问题。是否有某种内省可以告诉您正确的异常类?
  • 也许我刚刚回答了我自己的问题。在捕捉到BaseException as e 之后,它告诉我这是一个 AttributeError,所以我可以使用它。

标签: python wmi


【解决方案1】:

WMI 包有它自己的异常类型的创建。看起来它在您的示例中提出了它。

from wmi.wmi import x_wmi

try:
    numa = c.Win32_PerfFormattedData_PerfOS_NUMANodeMemory()

except x_wmi:
    logger.error('Failed to read NUMA status.')

【讨论】:

  • 你是怎么想出来的?
  • 我只是在github上查看了他们的源代码-在文件wmi.py中你可以看到对应的类
猜你喜欢
  • 2018-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-23
  • 2010-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多