Read osx notification in Python

Question:

I need to launch an application on reading a Notification center notification on osx. Is there any python library for reading the notification center notifications?

Asked By: Prasanth P

||

Answers:

Note: I did not try any of this as I do not have a machine running OSX at the moment, but from what I googled:

You could try adding an AppleScript snippet in your python code that uses System Events and Notification Center to parse all available notifications and return them to your stdout and parse the output directly in your code.

Source for getting all available notifications: https://macosxautomation.com/mavericks/notifications/01A.html. The part that should interest you is the code of the getNotificationTitles function. The bad part is that in that implementation you only get their titles, not the full notification, so you might have to parse different areas to get the full notification body.

Source for running it and getting the result: How do I embed an AppleScript in in a Python script?.

Another approach would be to use the terminal-notifier cli tool’s -list argument (as a shell command inside your script) and then parse the results.

There’s also a python wrapper for this tool available. The implementation contains a list() function which promises to work just the cli tool just that you wont need to spawn any shells from your own code and parse their stdouts.

Answered By: BoboDarph

I believe you will be able to do this with pyobjc. If you take a look at part of the code in macos-notifications repository, you’d find the userNotificationCenter_didDeliverNotification_ listener. This will get events the moment notifications are delivered. This does not only capture the notifications that you deliver using that application but for any notification. You could tweak the code a little and give it a try 🙂

Answered By: Jorrick Sleijster