Search code examples
pythonmacospython-2.7automation

Read osx notification in Python


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?


Solution

  • 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.