【发布时间】:2013-04-07 22:19:51
【问题描述】:
我正在尝试通过 python 连接到 Mountain Lion 通知中心。我已经安装了 pyobjc 并按照here 和here 的说明进行操作。另见:Working with Mountain Lion's Notification Center using PyObjC
这是我的代码:
import Foundation, objc
import AppKit
import sys
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
def notify(title, subtitle, info_text, delay=0, sound=False, userInfo={}):
""" Python method to show a desktop notification on Mountain Lion. Where:
title: Title of notification
subtitle: Subtitle of notification
info_text: Informative text of notification
delay: Delay (in seconds) before showing the notification
sound: Play the default notification sound
userInfo: a dictionary that can be used to handle clicks in your
app's applicationDidFinishLaunching:aNotification method
"""
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)
当我用参数调用通知函数时,我得到一个属性错误:
AttributeError: 'NoneType' object has no attribute 'scheduleNotification_'
我不明白为什么 NSUserNotificationCenter.defaultUserNotificationCenter() 返回一个 NoneType 对象。我无法在互联网或 SO 上查询有关此事的任何内容。
【问题讨论】:
-
难道你不能只用三行代码 (
import objc; NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter'); print NSUserNotificationCenter.defaultUserNotificationCenter()) 而不是整个函数来重现这个吗? -
啊!我想我可以!
-
FWIW,三行测试适用于我使用当前的 MacPorts
python27(@2.7.3_1) 和py27-pyobjc(@2.5.1_0):它返回_NSConcreteUserNotificationCenter的实例. -
就此而言,三行测试也适用于我在 OS X 10.8.3 中使用当前 Apple 提供的系统 Python 2.7.2 (
/usr/bin/python2.7)。 Apple 在其系统 Python 中发布了一个 PyObjC 版本。 -
谢谢内德!我注意到它也适用于我使用默认的 python 2.7.2。但是,当我在 Enthought Python 的 64 位安装上使用 easy_install 安装 PyObjC 时,就会出现我上面提出的问题。目前我想我会在这个脚本中继续使用系统默认的python。
标签: python osx-mountain-lion nsnotificationcenter pyobjc nsusernotificationcenter