python3-xlib

0.15 · active · verified Sat Apr 11

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

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an X server, retrieve the root window, and query the current input focus. It includes error handling for common connection issues and ensures the display connection is properly closed.

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.")

view raw JSON →