【发布时间】: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,所以我可以使用它。