59

使用 python 我想向 OSX 通知中心发布消息。我需要使用什么库?我应该在objective-c中编写一个程序,然后从python调用该程序吗?


更新

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

4

7 回答 7

141

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

import os

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

notify("Title", "Heres an alert")

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

更新:这应该适用于任何字符串,无需转义任何东西。它通过将原始字符串作为 args 传递给苹果脚本而不是试图将它们嵌入到苹果脚本程序的文本中来工作。

import subprocess

CMD = '''
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'!@#$%^&*()"')
于 2016-12-25T02:01:55.583 回答
69

您应该首先使用 Ruby 安装终端通知程序,例如:

$ [sudo] gem install terminal-notifier

然后您可以使用以下代码:

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!')

你去吧:

在此处输入图像描述

于 2013-07-15T10:08:20.330 回答
17

复制自: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")
于 2014-06-01T13:51:02.577 回答
8

对于仅 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"]])

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

于 2014-02-03T18:10:40.047 回答
5

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

安装

点安装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())
于 2020-05-14T04:17:48.620 回答
4

如果您还希望脚本能够通过其他设备与您通信,请尝试ntfy 。

安装

[sudo] pip install ntfy 

其中pip是指目标 Python 版本的 Package Installer

对于 Python3 安装:

[sudo] pip3 install ntfy    

用法

我使用这个简单的函数来通知有关命令执行和下载完成:

def notification(title, message):
    """Notifies the logged in user about the download completion."""

    import os
    cmd = 'ntfy -t {0} send {1}'.format(title, message)
    os.system(cmd)

notification("Download Complete", "Mr.RobotS01E05.mkv saved at /path")

ntfy的优势

  1. 该工具非常方便,因为它将所有通知直接记录到通知中心,而不是引用其他第三方应用程序。

  2. 多个后端支持:此工具可以通过 PushBullet、SimplePush、Slack、Telegram 等服务通过任何设备连接到您。在此处查看支持的后端服务的完整列表。

于 2017-04-03T18:25:01.847 回答
4

这是一种方法(您需要 Foundation 模块):

from Foundation import NSUserNotification
from Foundation import NSUserNotificationCenter
from Foundation import NSUserNotificationDefaultSoundName


class Notification():
    def notify(self, _title, _message, _sound = False):
        self._title = _title
        self._message = _message
        self._sound = _sound

        self.notification = NSUserNotification.alloc().init()
        self.notification.setTitle_(self._title)
        self.notification.setInformativeText_(self._message)
        if self._sound == True:
            self.notification.setSoundName_(NSUserNotificationDefaultSoundName)

        center = NSUserNotificationCenter.defaultUserNotificationCenter()
        center.deliverNotification_(self.notification)

N = Notification()
N.notify(_title="SOME", _message="Something", _sound=True)

这仅适用于 MAC。希望你喜欢!

于 2018-04-18T00:04:27.960 回答