wmctrl

0.5 · maintenance · verified Thu Apr 16

The Python `wmctrl` library (version 0.5) provides a wrapper around the `wmctrl` command-line utility, enabling programmatic control of windows within the X Window System. It allows Python scripts to query window information, activate windows, and perform actions like resizing or moving. The library follows a stable release cadence, with updates typically occurring years apart, reflecting its role as an interface to a mature external tool.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to list active windows and all open windows using the `wmctrl` library's `get_windows()` and `get_active_window()` functions. It also shows how to activate a window and includes an example of directly invoking the `wmctrl` command-line utility via `subprocess` for more granular control like moving and resizing. Ensure the `wmctrl` command-line utility is installed on your system.

import os
from wmctrl import get_windows, get_active_window

# Ensure wmctrl command-line utility is installed
if os.system('which wmctrl > /dev/null') != 0:
    print("Error: 'wmctrl' command-line utility not found. Please install it.")
    print("e.g., sudo apt-get install wmctrl (Debian/Ubuntu)")
    exit(1)

print("--- Active Window ---")
active_window = get_active_window()
if active_window:
    print(f"ID: {active_window.id}, Name: {active_window.wm_name}, Class: {active_window.wm_class}")
else:
    print("No active window found.")

print("\n--- All Windows ---")
windows = get_windows()
if windows:
    for w in windows:
        print(f"ID: {w.id}, Desktop: {w.desktop}, Name: {w.wm_name[:40]}...")
else:
    print("No windows found.")

# Example of activating a specific window by its name (if it exists)
# Note: This is an example, ensure a window with 'Firefox' in its name is open.
firefox_window = next((w for w in windows if 'Firefox' in w.wm_name), None)
if firefox_window:
    print(f"\nActivating Firefox window: {firefox_window.wm_name}")
    firefox_window.activate()
else:
    print("\nFirefox window not found to activate.")

# Example of moving/resizing a window using wmctrl command directly via subprocess
# Requires the window ID (e.g., from an active window or a search)
import subprocess
if active_window:
    print(f"\nAttempting to move active window {active_window.id} to 100,100 with size 800x600...")
    # Gravity 0, X=100, Y=100, Width=800, Height=600. -1 means keep current.
    try:
        subprocess.run(['wmctrl', '-ir', active_window.id, '-e', '0,100,100,800,600'], check=True)
        print("Window moved/resized (check your desktop).")
    except subprocess.CalledProcessError as e:
        print(f"Failed to move/resize window: {e}")

view raw JSON →