Python post OSX notification

Używając Pythona chcę wysłać wiadomość do OSX Notification Center. Z jakiej biblioteki muszę korzystać? czy powinienem napisać program w objective-c, a następnie wywołać go z Pythona?


Update

Jak uzyskać dostęp do funkcji Centrum powiadomień dla wersji 10.9, takich jak przyciski i pole tekstowe?

Author: kyle k, 2013-07-15

6 answers

Powinieneś najpierw zainstalować terminal-notifier z Rubim na przykład:

$ [sudo] gem install terminal-notifier

I wtedy możesz użyć tego kodu:

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

I proszę bardzo:

Tutaj wpisz opis obrazka

 47
Author: Peter Varo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-04 03:23:19

Wszystkie pozostałe odpowiedzi wymagają bibliotek stron trzecich; ta nie wymaga niczego. Po prostu używa skryptu apple, aby utworzyć powiadomienie:

import os

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

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

Zauważ, że ten przykład nie zawiera cudzysłowów, podwójnych cudzysłowów ani innych znaków specjalnych, więc znaki te nie będą działać poprawnie w tekście lub tytule powiadomienia.

 50
Author: Christopher Shroba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-25 02:32:32

Kopia z: https://gist.github.com/baliw/4020619

Podążanie za mną działa.
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")
 14
Author: sesame,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-01 13:51:02

Dla implementacji Pythona, zmodyfikowałem kod, który ktoś opublikował jako część innego powiązanego pytania i działa dobrze dla mnie:

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

Możesz wyczyścić deklaracje importu, aby usunąć niepotrzebne import.

 8
Author: Simon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-03 18:10:40

Spróbuj ntfy jeśli chcesz również, aby skrypt mógł komunikować się z Tobą za pośrednictwem innych urządzeń.

Instalacja

[sudo] pip install ntfy 

Gdzie pip odnosi się do instalatora pakietu docelowej wersji Pythona

Dla instalacji Python3:

[sudo] pip3 install ntfy    

Użycie

Używam tej prostej funkcji do powiadamiania o wykonaniu poleceń i zakończeniu pobierania:

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

Zalety ntfy

  1. To narzędzie jest bardzo przydatne ponieważ rejestruje wszystkie powiadomienia bezpośrednio do centrum powiadomień, a nie odnosi się do innej aplikacji innej firmy.

  2. Obsługa wielu backendów: to narzędzie może łączyć się z Tobą za pośrednictwem dowolnego urządzenia za pośrednictwem usług takich jak PushBullet, SimplePush, Slack, Telegram itp. Sprawdź całą listę obsługiwanych usług backend tutaj .

 0
Author: Kshitij Saraogi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-03 18:25:01

Oto sposób (potrzebujesz modułu 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)

To działa tylko dla komputerów MAC. Mam nadzieję, że się spodoba!

 0
Author: Aditya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-18 00:04:27