DisplayNotFoundError
Xlib.error.DisplayNameError
Stack trace
Xlib.error.DisplayNameError: Can't connect to display ""
File "/usr/lib/python3/dist-packages/Xlib/display.py", line 123, in __init__
self._display = self._open_display(display_name)
File "/usr/lib/python3/dist-packages/Xlib/display.py", line 152, in _open_display
raise DisplayNameError("Can't connect to display %s" % display_name)
Why it happens
This error occurs because the DISPLAY environment variable, which tells X11 applications where to render the GUI, is either unset or set to an invalid value. Without this variable, the application cannot find the X server to connect to, resulting in a connection failure.
Detection
Check if the DISPLAY environment variable is set before launching GUI apps by inspecting os.environ['DISPLAY'] or running 'echo $DISPLAY' in the shell.
Causes & fixes
DISPLAY environment variable is not set in the shell or Python environment
Set the DISPLAY variable to the correct X server address, e.g., export DISPLAY=:0 or os.environ['DISPLAY'] = ':0' before running the GUI app.
Running GUI app in a headless environment without an X server
Use a virtual framebuffer like Xvfb to provide a virtual display or run the app in an environment with a real X server.
SSH session without X11 forwarding enabled
Enable X11 forwarding by connecting with ssh -X or ssh -Y and ensure the remote DISPLAY variable is set automatically.
Incorrect or inaccessible X server address in DISPLAY variable
Verify the DISPLAY variable points to a valid and accessible X server, e.g., :0 or localhost:10.0, and that permissions allow connection.
Code: broken vs fixed
import os
from Xlib import display
# Missing DISPLAY environment variable causes error
# This line triggers DisplayNameError
d = display.Display()
print('Connected to display') import os
from Xlib import display
# Fix: Set DISPLAY environment variable before connecting
os.environ['DISPLAY'] = ':0' # Set to your X server address
d = display.Display()
print('Connected to display') Workaround
Wrap the display connection in try/except DisplayNameError and provide a fallback or log a clear error message instructing to set DISPLAY properly.
Prevention
Always ensure the DISPLAY environment variable is set correctly in your environment before launching GUI or X11-dependent applications, especially in remote or containerized setups.