Python X Library
python-xlib is a Python interface to the X11 Protocol, allowing Python programs to interact with the X Window System. It provides low-level access to Xlib functions and protocol extensions for X client programming. The current version is 0.33, and the library is actively maintained with releases addressing bugs and adding support for various X extensions.
Warnings
- breaking The method `add_extension_error` within extension handling was renamed to `extension_add_error`.
- gotcha Connecting to the X server (`Xlib.display.Display()`) frequently fails due to an unset or incorrect `DISPLAY` environment variable, an inactive X server, or insufficient permissions (especially for remote connections, requiring `xhost` configuration or SSH X forwarding).
- gotcha Versions prior to 0.29 might experience compatibility issues or crashes when running on Python 3.9 or newer, due to the removal of `array.array.tostring()` in Python 3.9.
- gotcha Older versions (pre-0.25) suffered from an increasing memory usage bug during display instantiation. Additionally, versions prior to 0.24 had general instability and connection issues, particularly on Python 3.x.
Install
-
pip install python-xlib
Imports
- Display
import Xlib.display display = Xlib.display.Display()
Quickstart
import Xlib.display
try:
# Connect to the default X server
# The DISPLAY environment variable typically specifies the X server.
# For remote connections, ensure X forwarding is set up or xhost permissions are granted.
display = Xlib.display.Display()
# Get the root window of the default screen
root = display.screen().root
# Print its geometry (x, y, width, height, border_width, depth)
geometry = root.get_geometry()
print(f"Root window geometry: {geometry}")
# Example: Query the current mouse pointer position
pointer_info = root.query_pointer()
print(f"Mouse pointer at: ({pointer_info.root_x}, {pointer_info.root_y})")
finally:
# Always close the display connection to release resources
if 'display' in locals() and display:
display.close()