Python发布osx通知

kyl*_*e k 44 python macos osx-mavericks

使用python我想将消息发布到OSX通知中心.我需要使用哪个库?我应该在objective-c中编写一个程序,然后从python中调用该程序?


更新

如何访问10.9通知中心的功能,如按钮和文本字段?

Chr*_*oba 82

这里的所有其他答案都需要第三方库; 这个不需要任何东西.它只使用一个苹果脚本来创建通知:

import os

def notify(title, text):
    os.system("""
              osascript -e 'display notification "{}" with title "{}"'
              """.format(text, title))

notify("Title", "Heres an alert")
Run Code Online (Sandbox Code Playgroud)

请注意,此示例不会转义引号,双引号或其他特殊字符,因此这些字符将无法在通知的文本或标题中正常工作.

  • @AndreaDiBiagio肯定!请看这里(http://apple.co/2mXi1Sc)如何通过通知播放声音,并在这里(http://apple.stackexchange.com/q/106904/)了解如何更改图标.添加声音很容易; 添加图像更加困难......你可能需要动态创建applescript文件并捆绑并在那里设置图像.祝好运! (5认同)
  • 那太棒了!您知道如何将通知保留更长时间,添加声音或图像吗? (3认同)
  • 如何增加长期停留时间? (2认同)
  • 您还可以[通过更改设置](https://apple.stackexchange.com/a/214598/100222)显示永久通知,或者通过将“notification”替换为“alert”或“dialog”来显示弹出警告上面的脚本。 (2认同)

Pet*_*aro 55

您应首先使用Ruby 安装terminal-notifier,例如:

$ [sudo] gem install terminal-notifier
Run Code Online (Sandbox Code Playgroud)

然后你可以使用这段代码:

import os

# The notifier function
def 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 function
notify(title    = 'A Real Notification',
       subtitle = 'with python',
       message  = 'Hello, this is me, notifying you!')
Run Code Online (Sandbox Code Playgroud)

你去了:

在此输入图像描述

  • 有一个名为[pync]的Python项目(https://pypi.python.org/pypi/pync)包含终端通知程序.也许你可以更新答案提到它? (3认同)
  • 对于无需安装其他依赖项的简单解决方案,您可以使用AppleScript发布通知.请参阅[我的回答](http://stackoverflow.com/a/41318195/2874789)了解具体方法!(很抱歉在这里劫持评论,只是想确保人们知道没有安装任何东西是可能的:)) (3认同)

ses*_*ame 15

复制自:https://gist.github.com/baliw/4020619

以下为我工作.

import Foundation
import objc
import AppKit
import sys

NSUserNotification = 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")
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法自定义通知中显示的图标?消息没有换行,有什么解决方法吗? (2认同)

小智 9

对于仅Python的实现,我修改了某人发布的代码作为另一个相关问题的一部分,并且对我来说效果很好:

import mmap, os, re, sys
from PyObjCTools import AppHelper
import Foundation
import objc
import AppKit
import time
from threading import Timer

from datetime import datetime, date

# objc.setVerbose(1)

class MountainLionNotification(Foundation.NSObject):
    # Based on http://stackoverflow.com/questions/12202983/working-with-mountain-lions-notification-center-using-pyobjc

    def init(self):
        self = super(MountainLionNotification, self).init()
        if self is None: return None

        # Get objc references to the classes we need.
        self.NSUserNotification = objc.lookUpClass('NSUserNotification')
        self.NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')

        return self

    def clearNotifications(self):
        """Clear any displayed alerts we have posted. Requires Mavericks."""

        NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
        NSUserNotificationCenter.defaultUserNotificationCenter().removeAllDeliveredNotifications()

    def notify(self, title, subtitle, text, url):
        """Create a user notification and display it."""

        notification = self.NSUserNotification.alloc().init()
        notification.setTitle_(str(title))
        notification.setSubtitle_(str(subtitle))
        notification.setInformativeText_(str(text))
        notification.setSoundName_("NSUserNotificationDefaultSoundName")
        notification.setHasActionButton_(True)
        notification.setActionButtonTitle_("View")
        notification.setUserInfo_({"action":"open_url", "value":url})

        self.NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self)
        self.NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification)

        # Note that the notification center saves a *copy* of our object.
        return notification

    # We'll get this if the user clicked on the notification.
    def userNotificationCenter_didActivateNotification_(self, center, notification):
        """Handler a user clicking on one of our posted notifications."""

        userInfo = notification.userInfo()
        if userInfo["action"] == "open_url":
            import subprocess
            # Open the log file with TextEdit.
            subprocess.Popen(['open', "-e", userInfo["value"]])
Run Code Online (Sandbox Code Playgroud)

您可能会清理import语句以删除一些不需要的导入.


小智 5

另一种选择是一个python名为pync的库,也许它是一个更好的选择。pync是terminal-notifier命令行工具的简单 Python 包装器,它允许您将用户通知发送到 Mac OS X 10.10 或更高版本的通知中心。

安装:

pip安装pync

例子:

from pync import Notifier

Notifier.notify('Hello World')
Notifier.notify('Hello World', title='Python')
Notifier.notify('Hello World', group=os.getpid())
Notifier.notify('Hello World', activate='com.apple.Safari')
Notifier.notify('Hello World', open='http://github.com/')
Notifier.notify('Hello World', execute='say "OMG"')

Notifier.remove(os.getpid())

Notifier.list(os.getpid())
Run Code Online (Sandbox Code Playgroud)