使用PyObjC与Mountain Lion的通知中心一起使用
我正尝试从我的python脚本向Mountain
Lion发送通知,并对点击通知做出反应。到目前为止,发送通知的工作非常完美。但是,我仍然无法让Lion单击一次来回叫我的脚本。
这是我的工作。我实现了一个Notification类。该类实例的唯一目的是通过调用提供通知notify()
。用相同的方法,将对象设置为应用程序的委托。
import Foundation
import objc
import AppKit
class MountainLionNotification(Foundation.NSObject, Notification):
def notify(self, title, subtitle, text, url):
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
notification = NSUserNotification.alloc().init()
notification.setTitle_(str(title))
notification.setSubtitle_(str(subtitle))
notification.setInformativeText_(str(text))
notification.setSoundName_("NSUserNotificationDefaultSoundName")
notification.setUserInfo_({"action":"open_url", "value":url})
AppKit.NSApplication.sharedApplication().setDelegate_(self)
NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)
def applicationDidFinishLaunching_(self, sender):
userInfo = sender.userInfo()
if userInfo["action"] == "open_url":
import subprocess
subprocess.Popen(['open', userInfo["value"]])
现在,我希望applicationDidFinishLaunching_()
在单击通知时会被调用。不幸的是,这永远不会发生。我究竟做错了什么?
-
好,找到了。没有跑
AppHelper.runEventLoop()
。显然是facepalm错误。以下代码有效:class MountainLionNotification(Foundation.NSObject, Notification): def notify(self, title, subtitle, text, url): NSUserNotification = objc.lookUpClass('NSUserNotification') NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter') notification = NSUserNotification.alloc().init() notification.setTitle_(str(title)) notification.setSubtitle_(str(subtitle)) notification.setInformativeText_(str(text)) notification.setSoundName_("NSUserNotificationDefaultSoundName") notification.setHasActionButton_(True) notification.setOtherButtonTitle_("View") notification.setUserInfo_({"action":"open_url", "value":url}) NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self) NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification) def userNotificationCenter_didActivateNotification_(self, center, notification): userInfo = notification.userInfo() if userInfo["action"] == "open_url": import subprocess subprocess.Popen(['open', userInfo["value"]])