Python PyAutoGUI return "ImageNotFoundException",但 "except" 不将其识别为异常

Python PyAutoGUI return "ImageNotFoundException", but "except" doesn't recognise it as an exception

使用以前版本的 pyautogui,当找不到图像时 return 是 "None",所以我用 except TypeError: 来处理它。 但是自更新(版本 0.9.41)以来,它无法正常工作,因为它是 returning ImageNotFoundException,但它未被识别为异常。当我尝试执行 except ImageNotFoundException: 时出现错误:

[E0712] Catching an exception which doesn't inherit from Exception: ImageNotFoundException

应该如何处理这个错误?

我遇到了和你一样的问题,也想不通为什么不能用 except 处理这个问题。现在我已经在 python 3.7 上弄明白了,如果你已经安装了 PyScreeze 包,这应该可以工作: 从 pyscreeze 导入 ImageNotFoundException

希望对您有所帮助:)

这适用于 pyautogui 0.9.52python 3.9.0

import pyautogui

# force use of ImageNotFoundException
pyautogui.useImageNotFoundException()

try:
    location = pyautogui.locateOnScreen('foo.png')
    print('image found')
except pyautogui.ImageNotFoundException:
    print('ImageNotFoundException: image not found')

我在本页 locateCenterOnScreen doesn't raise ImageNotFoundException. · Issue #441 · asweigart/pyautogui 中找到了 useImageNotFoundException() 部分。如果不调用 useImageNotFoundException(),则 locateOnScreen() 只是 returns None.

只需强制 pyautogui 使用 ImageNotFoundException。初始化pyautogui时使用这一行:

pyautogui.useImageNotFoundException()

不要使用 pyscreeze 的 ImageNotFoundException。 正如我们在 class ImageNotFoundException 定义中看到的那样,开发人员指出这不是一个理想的用途:

class ImageNotFoundException(PyAutoGUIException):
"""
This exception is the PyAutoGUI version of PyScreeze's `ImageNotFoundException`, which is raised when a locate*()
function call is unable to find an image.

Ideally, `pyscreeze.ImageNotFoundException` should never be raised by PyAutoGUI.
"""