Is there a way to find the application name of the current active window at a given time on Mac OS X using Python?
import time import win32ui from typing import Optional from ctypes import wintypes, windll, create_unicode_buffer def getForegroundWindowTitle() -> Optional[str]: hWnd = windll. user32. GetForegroundWindow() length = windll. user32.
The Apple-provided build of Python is installed in /System/Library/Frameworks/Python. framework and /usr/bin/python , respectively.
On MacOS, search for a program called terminal. You can do so by pressing the command key (⌘) + space bar. This will open up the Spotlight search bar, in which you start typing the word 'terminal'. Once you started the terminal, enter python3 to open the Python REPL.
This should work:
#!/usr/bin/python
from AppKit import NSWorkspace
activeAppName = NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName']
print activeAppName
Only works on Leopard, or on Tiger if you have PyObjC installed and happen to point at the right python binary in line one (not the case if you've installed universal MacPython, which you'd probably want to do on Tiger). But Peter's answer with the Carbon way of doing this will probably be quite a bit faster, since importing anything from AppKit in Python takes a while, or more accurately, importing something from AppKit for the first time in a Python process takes a while.
If you need this inside a PyObjC app, what I describe will work great and fast, since you only experience the lag of importing AppKit once. If you need this to work as a command-line tool, you'll notice the performance hit. If that's relevant to you, you're probably better off building a 10 line Foundation command line tool in Xcode using Peter's code as a starting point.
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