I’ve posted this question on StackOverflow before, but it seems too simple or that I did a superficial search to solve this problem, so I’ll post my problem here as well. (also to reach more people)
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 am using
except Exception:, but it is not very nice as a solution and is too general:
import os try: import pyautogui as pag except Exception: os.system("xhost +SI:localuser:root") import pyautogui as pag
I’ve alredy saw:
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
beacause X server need the variable DISPLAY to run, but it’s confusing, long and unreadable.