You could do something along the lines of
try:
import Xlib
except ImportError:
# do non-X11 things
else:
# do X11 things
or you could interrogate the exception object more closely
try:
thing_that_might_fail()
except Exception as e:
if type(e).__name__ == 'DisplayConnectionError':
print('I know how to handle this!')
else:
raise
As for your specific problem: Are you sure you want to call xhost
from your program? I’d have thought that if the user starts your program without the proper X11 access, the program should fail rather than reconfigure the system.
But by all means catch the exception properly in order to print a helpful error message.