简体   繁体   中英

How to catch an external exception in python?

I'm writing a simple python script to move the mouse and i'm using pyautogui to do it. The script must work both on Windows and Linux . The problem is that when i use linux Xlib raise Xlib.error.DisplayConnectionError . To solve this I used the try/catch clause to import pyautogui, but I don't know how to catch Xlib.error.DisplayConnectionError. As a workaround i'm using except Exception: , but it isn't very nice:

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

I've alredy saw:

Catching exceptions raised in imported modules

but i can't import Xlib on Windows.

One solution seems to be:

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

but it's confusing, long and unreadable.

You can catch a general exception and then simply check the specific type of it, without importing the external module:

try:
    import 𝙢𝙤𝙙𝙪𝙡𝙚
except Exception as e:
    if e.__type__ == '𝙀𝙭𝙘𝙚𝙥𝙩𝙞𝙤𝙣𝙉𝙖𝙢𝙚':
        #do things...
    else:
        #do other things...

Suggestion by @tjollans

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM