1

I have following code which use infinite loop to check if active window has changed.This program prints the name of current window when active window changes. There must be better way to do this. how can a keep my python code always listening to active window change without infinite loop?

import subprocess
import psutil

pid = subprocess.check_output(["xdotool", "getactivewindow", "getwindowpid"]).decode("utf-8").strip()
prevpid=pid
print(pid)
while(True):
    pid = subprocess.check_output(["xdotool", "getactivewindow", "getwindowpid"]).decode("utf-8").strip()
    if prevpid!=pid:
        process=psutil.Process(int(pid))
        processName=process.name()
        print("Current Active Process is "+processName)
        prevpid=pid
Jacob Vlijm
  • 3,099
  • 1
  • 21
  • 37
Aayush Neupane
  • 1,066
  • 1
  • 12
  • 29
  • Take a look at this https://stackoverflow.com/questions/60141048/get-notifications-when-active-x-window-changes-using-python-xlib – Philippe Mar 21 '21 at 10:41

1 Answers1

1

If you are on X, instead of polling, it is much better to use the Wnck.Screen's active_window_changed signal, running from a Gtk loop. In a simple example:

#!/usr/bin/env python3
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('Wnck', '3.0')
from gi.repository import Gtk, Wnck


def dosomething(screen, previous_window):
    try:
        print(
            previous_window.get_name(), "||",
            screen.get_active_window().get_name()
        )
        # or run any action
    except AttributeError:
        pass


wnck_scr = Wnck.Screen.get_default()
wnck_scr.force_update()
wnck_scr.connect("active-window-changed", dosomething)
Gtk.main()
Jacob Vlijm
  • 3,099
  • 1
  • 21
  • 37