Follow active applications on Mac with Python

It's hard to remember Objective-C, so I've just scratched it, but I wrote it using Python (and PyObjC):

active_app_logger.py


from AppKit import *
from PyObjCTools import AppHelper

def main():
    nc = NSWorkspace.sharedWorkspace().notificationCenter()
    nc.addObserver_selector_name_object_(
        Observer.new(),
        "handle:",
        NSWorkspaceDidActivateApplicationNotification,
        None
    )
    AppHelper.runConsoleEventLoop(installInterrupt=True)

class Observer(NSObject):
    def handle_(self, noti):
        """Process called when the active application is switched"""
        info = noti.userInfo().objectForKey_(NSWorkspaceApplicationKey)
        for n in ["bundleIdentifier", "localizedName", "bundleURL",
                  "executableURL", "launchDate"]:
            v = info.valueForKey_(n)
            print("%s (%s):\t%s" % (n, v.className(), v))
        print("--")

main()

Run it on your device and switch applications in the order of Google Chrome → iTerm:

$ python cocoa_active_window.py
bundleIdentifier (__NSCFString):        com.google.Chrome
localizedName (__NSCFString):   Google Chrome
bundleURL (NSURL):      file:///Applications/Google%20Chrome.app
executableURL (NSURL):  file:///Applications/Google%20Chrome.app/Contents/MacOS/Google%20Chrome
launchDate (__NSDate):  2015-01-02 05:09:26 +0000
--
bundleIdentifier (__NSCFString):        com.googlecode.iterm2
localizedName (NSTaggedPointerString):  iTerm
bundleURL (NSURL):      file:///Applications/iTerm.app
executableURL (NSURL):  file:///Applications/iTerm.app/Contents/MacOS/iTerm
launchDate (__NSTaggedDate):    2015-01-02 05:59:29 +0000
--

PyObjC must be installed to run this script:

$ sudo pip install pyobjc

The operating environment of the script is:

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.10.1
BuildVersion:   14B25
$ xcodebuild -version
Xcode 6.1.1
Build version 6A2008a
$ python --version
Python 2.7.6
$ pip show 'pyobjc' | grep Version
Version: 3.0.4

I chose PyObjC because it seemed to have more materials than Ruby (RubyCocoa), which I'm used to a little, but if neither Python nor PyObjC can be used easily in Objective-C and I have never created a Mac OS X application, I will obediently start from Objective-C. It might have been easier to remember. It was hard.

It seems that you need to touch NSAccessibility to get information on the active window, so give up. Is NSAccessibility an API with a solid policy that allows access to critical information? Also, I couldn't find it in PyObjC, but isn't it bound?

Recommended Posts

Follow active applications on Mac with Python
python on mac
Build Python environment with Anaconda on Mac
Install Python on Mac
Install Python 3 on Mac
Install Python 3.4 on Mac
Try working with Mongo in Python on Mac
Put Python 2.7.x on Mac OSX 10.15.5 with pyenv
Install pygame on python3.4 on mac
Python3 + Django ~ Mac ~ with Apache
Automatic follow on Twitter with python and selenium! (RPA)
Handling of python on mac
Update python on Mac to 3.7-> 3.8
Install pandas 0.14 on python3.4 [on Mac]
Notes on installing Python on Mac
I want to AWS Lambda with Python on Mac!
Using OpenCV with Python @Mac
Machine learning environment settings based on Python 3 on Mac (coexistence with Python 2)
Building a Python environment on Mac
If python on mac goes missing
tensor flow with anaconda on mac
Getting Started with Python Web Applications
Create a Python environment on Mac (2017/4)
Python environment construction memo on Mac
Install Python 3.7 Anaconda on MAC, but Python 2
Install python3 on Mac (El Capitan)
Environment construction of python3.8 on mac
Notes on using rstrip with python.
If Python 3.5.0 installation fails on Mac
Steps to install python3 on mac
Getting started with Python 3.8 on Windows
Install python with mac vs code
Call C / C ++ from Python on Mac
[Memo] Tweet on twitter with python
Update Python on Mac from 2 to 3
Get started with the Python framework Django on Mac OS X
Build a Python environment on your Mac with Anaconda and PyCharm
Error and solution when installing python3 with homebrew on mac (catalina 10.15)
Install lp_solve on Mac OS X and call it with python.
Migrate Django applications running on Python 2.7 to Python 3.5
[Python] Building an environment with Anaconda [Mac]
Run servo with Python on ESP32 (Windows)
Introducing MAMP + Python + SQLAlchemy (Mysql-Python) on Mac
Map rent information on a map with python
[C] [python] Read with AquesTalk on Linux
Notes on doing Japanese OCR with Python
Follow Python style guides with Atom (flake8)
How to erase Python 2.x on Mac.
scipy stumbles with pip install on python 2.7.8
Notes on building Python and pyenv on Mac
Download files on the web with Python
Video processing using Python + OpenCV on Mac
Installing PIL with Python 3.x on macOS
Working with GPS on Raspberry Pi 3 Python
Put MeCab binding for Python with pip on Windows, mac and Linux
Send and receive binary data via serial communication with python3 (on mac)
Create a Python3 environment with pyenv on Mac and display a NetworkX graph
Getting started with Python with 100 knocks on language processing
Statistics with python
Strategy on how to monetize with Python Java
Build python environment with pyenv on EC2 (ubuntu)