Skip to content

Instantly share code, notes, and snippets.

@amomchilov
Forked from pudquick/visible_apps.py
Last active January 19, 2023 12:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amomchilov/096ce5ceb9f4fca942ae0dd37066bc11 to your computer and use it in GitHub Desktop.
Save amomchilov/096ce5ceb9f4fca942ae0dd37066bc11 to your computer and use it in GitHub Desktop.
Getting the list of visible apps (think: Force Quit) in macOS via Python and PyObjC
#!/usr/bin/env python3
#ref: https://gist.github.com/pudquick/eebc4d569100c8e3039bf3eae56bee4c
from Foundation import NSBundle
import objc # pip3 install objc
CoreServices = NSBundle.bundleWithIdentifier_('com.apple.CoreServices')
functions = [
('_LSCopyRunningApplicationArray', b'@I'),
('_LSCopyApplicationInformation', b'@I@@'),
]
constants = [
('_kLSApplicationTypeKey', b'@'),
('_kLSApplicationForegroundTypeKey', b'@'),
('_kLSDisplayNameKey', b'@'),
]
objc.loadBundleFunctions(CoreServices, globals(), functions)
objc.loadBundleVariables(CoreServices, globals(), constants)
kLSDefaultSessionID = 0xfffffffe # The actual value is `int -2`
kLSCurrentSessionID = 0xffffffff # The actual value is `int -1`
app_asns = _LSCopyRunningApplicationArray(kLSDefaultSessionID)
app_infos = [_LSCopyApplicationInformation(kLSDefaultSessionID, asn, None) for asn in app_asns]
visible_app_infos = [x for x in app_infos if x.get(_kLSApplicationTypeKey, None) == _kLSApplicationForegroundTypeKey]
visible_apps = sorted([x.get(_kLSDisplayNameKey) for x in visible_app_infos])
print(visible_apps)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment