Python post osx notification Python post osx notification python python

Python post osx notification


All the other answers here require third party libraries; this one doesn't require anything. It just uses an apple script to create the notification:

import osdef notify(title, text):    os.system("""              osascript -e 'display notification "{}" with title "{}"'              """.format(text, title))notify("Title", "Heres an alert")

Note that this example does not escape quotes, double quotes, or other special characters, so these characters will not work correctly in the text or title of the notification.

Update: This should work with any strings, no need to escape anything. It works by passing the raw strings as args to the apple script instead of trying to embed them in the text of the apple script program.

import subprocessCMD = '''on run argv  display notification (item 2 of argv) with title (item 1 of argv)end run'''def notify(title, text):  subprocess.call(['osascript', '-e', CMD, title, text])# Example uses:notify("Title", "Heres an alert")notify(r'Weird\/|"!@#$%^&*()\ntitle', r'!@#$%^&*()"')


You should install terminal-notifier first with Ruby for example:

$ [sudo] gem install terminal-notifier

And then you can use this code:

import os# The notifier functiondef notify(title, subtitle, message):    t = '-title {!r}'.format(title)    s = '-subtitle {!r}'.format(subtitle)    m = '-message {!r}'.format(message)    os.system('terminal-notifier {}'.format(' '.join([m, t, s])))# Calling the functionnotify(title    = 'A Real Notification',       subtitle = 'with python',       message  = 'Hello, this is me, notifying you!')

And there you go:

enter image description here


copy from: https://gist.github.com/baliw/4020619

following works for me.

import Foundationimport objcimport AppKitimport sysNSUserNotification = objc.lookUpClass('NSUserNotification')NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')def notify(title, subtitle, info_text, delay=0, sound=False, userInfo={}):    notification = NSUserNotification.alloc().init()    notification.setTitle_(title)    notification.setSubtitle_(subtitle)    notification.setInformativeText_(info_text)    notification.setUserInfo_(userInfo)    if sound:        notification.setSoundName_("NSUserNotificationDefaultSoundName")    notification.setDeliveryDate_(Foundation.NSDate.dateWithTimeInterval_sinceDate_(delay, Foundation.NSDate.date()))    NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)notify("Test message", "Subtitle", "This message should appear instantly, with a sound", sound=True)sys.stdout.write("Notification sent...\n")