'finding the app window currently in focus on Mac OSX

I am writing a desktop usage statistics app. It runs a background daemon which wakes up at regular intervals, finds the name of the application window currently in focus and logs that data in database.

I manage to do this on Linux desktop with help of xprop utility (you can find it here).

How can I do the same on Mac OSX? Is there a direct/indirect way to do this from a python script? (PyObjC?)



Solution 1:[1]

You can do this with AppleScript:

Get the title of the current active Window/Document in Mac OS X

You can try using appscript to generate AppleScript events from python.

Solution 2:[2]

It should be possible to get the active window by using AppKit like the following

from AppKit import NSWorkspace

workspace = NSWorkspace.sharedWorkspace()
active_app = workspace.activeApplication()['NSApplicationName']

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 jmlw