I'd like to be able to track which application is currently focused on my X11 display from Python. The intent is to tie it into a timetracking tool so that I can keep track of how much time I spend being unproductive.
I already found this code at http://thpinfo.com/2007/09/x11-idle-time-and-focused-window-in.html:
import Xlib.display
display = Xlib.display.Display()
focus = display.get_input_focus()
print "WM Class: %s" % ( focus.focus.get_wm_class(), )
print "WM Name: %s" % ( focus.focus.get_wm_name(), )
However, it doesn't seem to work for me. Apparently, no matter which application is focused, both get_wm_class() and get_wm_name() just return None.
Of course the solution needs to work with all these new fangled window managers like Compiz and such.
Whoo! I figured it out myself:
import Xlib.display
display = Xlib.display.Display()
window = display.get_input_focus().focus
wmname = window.get_wm_name()
wmclass = window.get_wm_class()
if wmclass is None and wmname is None:
window = window.query_tree().parent
wmname = window.get_wm_name()
print "WM Name: %s" % ( wmname, )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With