Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the Current Active Window in Mac OS X using Python

Is there a way to find the application name of the current active window at a given time on Mac OS X using Python?

like image 212
Moiz Avatar asked Dec 16 '08 22:12

Moiz


People also ask

How do I get the active window in 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.

Where is Python interpreter OSX?

The Apple-provided build of Python is installed in /System/Library/Frameworks/Python. framework and /usr/bin/python , respectively.

How do I launch Python on Mac?

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.


1 Answers

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.

like image 172
Dirk Stoop Avatar answered Nov 02 '22 13:11

Dirk Stoop