Уведомление о публикации python post osx
Использование python Я хочу отправить сообщение в Центр уведомлений OSX.
Какую библиотеку мне нужно использовать? должен ли я написать программу в objective-c, а затем вызвать эту программу из python?
Обновление
Как мне получить доступ к функциям центра уведомлений для 10.9, таких как кнопки и текстовое поле?
Ответы
Ответ 1
Вы должны установить terminal-notifier сначала с помощью 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!')
И вот вы:
![enter image description here]()
Ответ 2
Все остальные ответы здесь требуют сторонних библиотек; это ничего не требует. Он просто использует apple script для создания уведомления:
import os
def notify(title, text):
os.system("""
osascript -e 'display notification "{}" with title "{}"'
""".format(text, title))
notify("Title", "Heres an alert")
Обратите внимание, что в этом примере не выполняются кавычки, двойные кавычки или другие специальные символы, поэтому эти символы не будут работать корректно в тексте или заголовке уведомления.
Ответ 3
скопировать из: 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")
Ответ 4
Для реализации только 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"]])
Вероятно, вы можете очистить операторы импорта, чтобы удалить некоторые ненужные импорты.
Ответ 5
Попробуйте ntfy, если вы также хотите, чтобы script мог общаться с вами других устройств.
Установка
[sudo] pip install ntfy
где pip
относится к установщику пакетов целевой версии Python
Для установки 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
-
Этот инструмент весьма удобен, поскольку он регистрирует все уведомления непосредственно в Центре уведомлений, а не ссылается на другое стороннее приложение.
-
Поддержка нескольких бэкэдов: этот инструмент может подключаться к вам через любое устройство с помощью таких сервисов, как PushBullet, SimplePush, Slack, Telegram и т.д. Проверьте весь список поддерживаемых бэкэнд-сервисов здесь.