Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/293.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何确定正确的异常类_Python_Wmi - Fatal编程技术网

Python 如何确定正确的异常类

Python 如何确定正确的异常类,python,wmi,Python,Wmi,我正在使用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 F

我正在使用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
但进口失败:

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

WMI包创建了自己的异常类型。看起来它在你的例子中提出了这个问题

from wmi.wmi import x_wmi

try:
    numa = c.Win32_PerfFormattedData_PerfOS_NUMANodeMemory()

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


这与使用正确或不正确的异常类无关。导入模块:
导入pywintypes
。您不能在
导入内容中指定非模块。无论什么
。这是否回答了您的问题?我试过了;它没赶上火车exception@fooiey非常好,谢谢<代码>基本异常
有效。但我的问题的核心是,如果有一个新的(可能是未记录的)模块,您如何才能解决这个问题。是否有某种内省可以告诉你正确的异常类?也许我刚刚回答了我自己的问题。在将
BaseException捕获为e
后,它告诉我这是一个AttributeError,这样我就可以使用它了。你是怎么知道的?我只是在github上查看了它们的源代码-在文件wmi.py中,你可以看到相应的类
>>> sys.modules['pywintypes']
<module 'pywintypes' (C:\WINDOWS\SYSTEM32\pywintypes37.dll)>
>>> sys.modules['pywintypes'].com_error
<class 'pywintypes.com_error'>
from wmi.wmi import x_wmi

try:
    numa = c.Win32_PerfFormattedData_PerfOS_NUMANodeMemory()

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