【问题标题】:How to catch an external exception in python?如何在python中捕获外部异常?
【发布时间】:2021-06-13 13:07:54
【问题描述】:

我正在编写一个简单的 python 脚本来移动鼠标,我正在使用 pyautogui 来完成它。 脚本必须同时在 Windows 和 Linux 上运行。问题是when i use linux Xlib raise Xlib.error.DisplayConnectionError。为了解决这个问题,我使用 try/catch 子句导入 pyautogui,但我不知道如何捕获 Xlib.error.DisplayConnectionError。 作为一种解决方法,我使用except Exception:,但这不是很好:

import os
try:
    import pyautogui as pag
except Exception:
    os.system("xhost +SI:localuser:root")
    import pyautogui as pag

我已经看过了:

Catching exceptions raised in imported modules

但我无法在 Windows 上导入 Xlib。

一个解决方案似乎是:

import os
if 'DISPLAY' in os.environ:
    import Xlib
    try:
        import  pyautogui as pag
    except Xlib.error.DisplayConnectionError:
        os.system("xhost +SI:localuser:root")
        import  pyautogui as pag
else:
    import pyautogui as pag

但它令人困惑、冗长且难以阅读。

【问题讨论】:

    标签: python import try-catch python-module


    【解决方案1】:

    您可以捕获一般异常,然后简单地检查它的特定类型,而无需导入外部模块:

    try:
        import ??????
    except Exception as e:
        if e.__type__ == '?????????????':
            #do things...
        else:
            #do other things...
    

    Suggestion@tjollans

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2016-12-13
      • 1970-01-01
      • 2014-12-04
      • 1970-01-01
      • 2013-05-03
      • 2012-03-16
      相关资源
      最近更新 更多