我有一个脚本,它使用pygetwindow
模块在特定的窗口上执行一些操作。当脚本运行时,我得到以下异常:
File "C:\Program Files (x86)\Python38-32\lib\site-packages\pygetwindow\_pygetwindow_win.py", line 237, in activate
_raiseWithLastError()
File "C:\Program Files (x86)\Python38-32\lib\site-packages\pygetwindow\_pygetwindow_win.py", line 97, in _raiseWithLastError
raise PyGetWindowException('Error code from Windows: %s - %s' % (errorCode, _formatMessage(errorCode)))
pygetwindow.PyGetWindowException: Error code from Windows: 0 - The operation completed successfully.
我不介意异常发生,但我想要显式地捕获这个异常。我做了以下工作来尝试捕获这个异常:
try:
#implementation
except pygetwindow.PyGetWindowException:
#handle exception
和
try:
#implementation
except PyGetWindowException:
#handle exception
上述两种方法都不捕获异常。如果我使用上述两种方法之一,就会得到另一个例外:
NameError: name 'PyGetWindowException' is not defined
或
NameError: name 'pygetwindow' is not defined
我不想捕获通用Exception
,然后处理它,因为在发生其他异常的情况下,我想以不同的方式处理它。我是想抓住这个异常,还是有什么方法可以完全避免这个异常呢?
编辑:非常清楚,我已经导入了pygetwindow
。
发布于 2021-08-01 02:27:03
更新
从来源文件中可以清楚地看到,为了使用PyGetWindowException
,您需要专门导入异常(而不仅仅是import pygetwindow
)。因此,为了抓住例外情况,我们必须:
from pygetwindow import PyGetWindowException
在此导入之后,您可以正常地使用异常:
try:
#implementation
except PyGetWindowException:
#handle exception
更新2
另一种常见的方法是从一般异常到获取异常名称并进行比较。
try:
try:
#implementation
except Exception as e:
if e.__class__.__name__ == 'PyGetWindowException':
#handle exception
else:
raise e
except Exception as e:
#handle other exceptions except pygetwindow exception
原答案(不推荐)
在这个回答中找到了解决这个问题的方法。
从来源 of pygetwindow
中可以清楚地看到,无论何时提出PyGetWindowException
,都伴随着案文:
“Windows中的错误代码:”
它指示Windows提供的错误代码。
根据这些信息,我做了以下工作:
try:
try:
#Implementation
except Exception as e:
if "Error code from Windows" in str(e)
# Handle pygetwindow exception
else:
raise e
except Exception as e:
#handle other exceptions
这是另一种解决问题的方法(虽然第一种和第二种是正确和直接的解决方案)。
发布于 2021-07-31 07:39:27
您应该让import pygetwindow
在您的脚本乞求。它抱怨不知道pygetwindow
是什么。
https://stackoverflow.com/questions/68599793
复制相似问题