Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
python-xlib example which reacts to changing the active window
#!/usr/bin/env python
"""python-xlib example which reacts to changing the active window/title.
- Python
- python-xlib
Tested with Python 2.x because my Kubuntu 14.04 doesn't come with python-xlib
for Python 3.x.
Any modern window manager that isn't horrendously broken maintains an X11
property on the root window named _NET_ACTIVE_WINDOW.
Any modern application toolkit presents the window title via a property
named _NET_WM_NAME.
This listens for changes to both of them and then hides duplicate events
so it only reacts to title changes once.
from contextlib import contextmanager
import Xlib
import Xlib.display
# Connect to the X server and get the root window
disp = Xlib.display.Display()
root = disp.screen().root
# Prepare the property names we use so they can be fed into X11 APIs
NET_WM_NAME = disp.intern_atom('_NET_WM_NAME') # UTF-8
WM_NAME = disp.intern_atom('WM_NAME') # Legacy encoding
last_seen = { 'xid': None, 'title': None }
def window_obj(win_id):
"""Simplify dealing with BadWindow (make it either valid or None)"""
window_obj = None
if win_id:
window_obj = disp.create_resource_object('window', win_id)
except Xlib.error.XError:
yield window_obj
def get_active_window():
"""Return a (window_obj, focus_has_changed) tuple for the active window."""
win_id = root.get_full_property(NET_ACTIVE_WINDOW,
focus_changed = (win_id != last_seen['xid'])
if focus_changed:
with window_obj(last_seen['xid']) as old_win:
if old_win:
last_seen['xid'] = win_id
with window_obj(win_id) as new_win:
if new_win:
return win_id, focus_changed
def _get_window_name_inner(win_obj):
"""Simplify dealing with _NET_WM_NAME (UTF-8) vs. WM_NAME (legacy)"""
for atom in (NET_WM_NAME, WM_NAME):
window_name = win_obj.get_full_property(atom, 0)
except UnicodeDecodeError: # Apparently a Debian distro package bug
title = "<could not decode characters>"
if window_name:
win_name = window_name.value
if isinstance(win_name, bytes):
# Apparently COMPOUND_TEXT is so arcane that this is how
# tools like xprop deal with receiving it these days
win_name = win_name.decode('latin1', 'replace')
return win_name
title = "<unnamed window>"
return "{} (XID: {})".format(title,
def get_window_name(win_id):
"""Look up the window name for a given X11 window ID"""
if not win_id:
last_seen['title'] = "<no window id>"
return last_seen['title']
title_changed = False
with window_obj(win_id) as wobj:
if wobj:
win_title = _get_window_name_inner(wobj)
title_changed = (win_title != last_seen['title'])
last_seen['title'] = win_title
return last_seen['title'], title_changed
def handle_xevent(event):
# Loop through, ignoring events until we're notified of focus/title change
if event.type != Xlib.X.PropertyNotify:
changed = False
if event.atom == NET_ACTIVE_WINDOW:
if get_active_window()[1]:
changed = changed or get_window_name(last_seen['xid'])[1]
elif event.atom in (NET_WM_NAME, WM_NAME):
changed = changed or get_window_name(last_seen['xid'])[1]
if changed:
def handle_change(new_state):
"""Replace this with whatever you want to actually do"""
if __name__ == '__main__':
# Listen for _NET_ACTIVE_WINDOW changes
# Prime last_seen with whatever window was active when we started this
while True: # next_event() sleeps until we get an event

This comment has been minimized.

Copy link

commented Nov 1, 2017

Thanks a lot for this gist, I used to create a Steam "window manager", in a working in progress version of the steam-login project ( that is licensed under GPL-v2+.

I still didn't upload it, since I don't know the license for the code on your gist.

Can I use it in my GPL-v2+ project?



This comment has been minimized.

Copy link
Owner Author

commented Nov 2, 2017

I actually posted this as the "full version" of a code snippet I put up on StackOverflow, but you can consider it MIT-licensed if you'd like something more concrete.

Regardless of which terms you use it under, I'd appreciate a shout-out. Nothing fancy... sticking a code comment like this above it will do:

# Based on code by Stephan Sokolow
# Source:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.