Skip to content

Instantly share code, notes, and snippets.

@luckman212
Created May 10, 2019 05:15
Show Gist options
  • Save luckman212/91cdd9a08e98a9f01214bdfde3057e85 to your computer and use it in GitHub Desktop.
Save luckman212/91cdd9a08e98a9f01214bdfde3057e85 to your computer and use it in GitHub Desktop.
simple python script that prints the frontmost (aka focused) app
#!/usr/bin/python
# references
# https://developer.apple.com/documentation/appkit/nsworkspace
# https://bmn.name/post/2016/05/28/current-osx-app/
# https://stackoverflow.com/questions/28815863/how-to-get-active-window-title-using-python-in-mac
# https://apple.stackexchange.com/questions/123730/is-there-a-way-to-detect-what-program-is-stealing-focus-on-my-mac/
try:
from AppKit import NSWorkspace
except ImportError:
print "can't import AppKit -- maybe you're running python from homebrew?"
print "try running with /usr/bin/python instead"
exit(1)
from datetime import datetime
from time import sleep
last_active_name = None
while True:
active_app = NSWorkspace.sharedWorkspace().activeApplication()
if active_app:
if active_app['NSApplicationName'] != last_active_name:
last_active_name = active_app['NSApplicationName']
print '%s: [%s] %s (%s)' % (
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
active_app['NSApplicationProcessIdentifier'],
active_app['NSApplicationPath'],
active_app['NSApplicationName']
)
else:
if last_active_name:
print '%s: %s' % (
datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'*** no active app ***'
)
last_active_name = None
sleep(0.05)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment