Mac OS Notifications from Python - with PyCharm debugging :)
I wanted to create an application that notifies me of interesting things through different means (it could be an SMS, an email or… Mac OS neat notification system).
I found this Stack Overflow answer that explained how to do that from Python, and even letting you add an action button (something like “View”). Here’s that answer with a minor tweak on the init code (as the original way doesn’t work anymore)
… but things weren’t that simple. In order for an application to be able to send notifications, it needs to be part of an application bundle and have, on its Info.plist the CFBundleIdentifier key populated. As I’m using virtualenv, the application that’s being run is /path/to/my/virtualenv/bin/python and that obviously is not a bundle. Also, that’s what PyCharm uses, and I want to set up my script to be run as a launchd script. Some people suggested using py2app, but I wanted to be able to debug as needed.
Do you want to show alert notifications? (the ones that don’t disappear automatically and that let you use an action button) you need your Info.plist to have NSUserNotificationAlertStyle = alert (and enable them on System Preferences, or have your code signed)
The way I found to make all of that happen was:
create a python.app bundle containing an Info.plist inside of the environment, with a link to the python executable
create a python bash script on the environment that calls the python.app application
With your virtualenv activated, paste this and it will take care of everything for you
If you hate pasting so many lines (as I do), you can just do
And that should be it! you now have a python file on your environment that’s a bundle, and on pycharm you’ll be able to debug the notifications code and see the notifications pop up :) You can see my project here.