python3-xlib
python3-xlib is a Python binding for the X Window System protocol library (Xlib). It allows Python programs to interact with the X server, enabling tasks such as managing windows, drawing graphics, and handling input events directly. The current version is 0.15, and the library is maintained with infrequent but consistent updates.
Warnings
- breaking This library (`python3-xlib`) is a port for Python 3. It is not compatible with the older `python-xlib` library which was designed for Python 2. Code written for `python-xlib` will likely break.
- gotcha Connecting to the X server requires an active X server and the `DISPLAY` environment variable to be correctly set. If these conditions are not met, `Xlib.error.DisplayError` will be raised.
- gotcha Many Xlib operations are blocking. For applications requiring responsiveness or concurrent operations, it's crucial to use non-blocking methods where available or run Xlib operations in a separate thread/process.
- gotcha The `Xlib.display.Display` object holds a connection to the X server. Failing to call `display.close()` can lead to resource leaks on the X server or prevent the connection from being properly terminated.
Install
-
pip install python3-xlib
Imports
- Display
import Xlib.display display = Xlib.display.Display()
Quickstart
import Xlib.display
import Xlib.error
import os
try:
# Attempt to connect to the X server using the DISPLAY environment variable
# or a default if not set (e.g., for testing without a real X server).
# For actual usage, ensure DISPLAY is correctly set (e.g., ':0' or 'localhost:0').
display_name = os.environ.get('DISPLAY', ':0') # Use ':0' as a common default
display = Xlib.display.Display(display_name)
print(f"Successfully connected to X display: {display_name}")
# Get the root window of the default screen
root_window = display.screen().root
print(f"Root window ID: {root_window.id}")
# Query the input focus window
input_focus = display.get_input_focus()
if input_focus.focus:
print(f"Current input focus window ID: {input_focus.focus.id}")
else:
print("No specific window currently has input focus.")
except Xlib.error.DisplayError as e:
print(f"Error connecting to X display '{display_name}': {e}")
print("HINT: Ensure an X server is running and the DISPLAY environment variable is correctly set.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
finally:
if 'display' in locals() and display:
display.close()
print("Disconnected from X display.")