Python 发布 osx 通知

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17651017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:47:13  来源:igfitidea点击:

Python post osx notification

pythonmacososx-mavericks

提问by kyle k

Using python I am wanting to post a message to the OSX Notification Center. What library do I need to use? should i write a program in objective-c and then call that program from python?

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



update

更新

How do I access the features of notification center for 10.9 such as the buttons and the text field?

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

采纳答案by Peter Varo

You should install terminal-notifierfirst with Ruby for example:

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

$ [sudo] gem install terminal-notifier

And then you can use this code:

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

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

And there you go:

然后你去:

enter image description here

在此处输入图片说明

回答by Simon

For a Python only implementation, I've modified the code that someone posted as part of another related question, and is working well for me:

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

You could likely clean up the import statements to remove some unneeded imports.

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

回答by sesame

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

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

following works for me.

以下为我工作。

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")

回答by Christopher Shroba

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 os

def 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.

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

回答by Kshitij Saraogi

Try ntfyif you also want the script to be able to communicate with you over other devices.

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

Installation

安装

[sudo] pip install ntfy 

where piprefers to the Package Installer of the target Python version

wherepip指的是目标 Python 版本的 Package Installer

For Python3 installation:

对于 Python3 安装:

[sudo] pip3 install ntfy    

Usage

用法

I use this simple function for notifications regarding command executions and download completions:

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

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")

Advantages of ntfy

ntfy的优势

  1. This tool is quite handy as it logs all the notifications directly to the Notification Center rather than referring to other third-party application.

  2. Multiple Backend supports: This tool can connect to you over any device through services such as PushBullet, SimplePush, Slack, Telegram etc. Check the entire list of supported backend services here.

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

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

回答by Kshitij Saraogi

Here is a way (You need the Foundation module):

这是一种方法(您需要 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)

This works only for MAC. Hope you enjoy!

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

回答by Song Bi

Another choice is a pythonlib named pync, maybe it's a better choice. pyncis a simple Python wrapper around the terminal-notifiercommand-line tool, which allows you to send User Notifications to the Notification Center on Mac OS X 10.10, or higher.

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

Installation:

安装

pip install pync

pip安装pync

Examples:

例子

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())