J'ai écrit un code python pour obtenir du texte aléatoire dans un fichier .txt. Maintenant, je veux envoyer ce texte au hasard dans la zone de notification via la commande 'notify-send'. Comment faisons-nous cela?
J'ai écrit un code python pour obtenir du texte aléatoire dans un fichier .txt. Maintenant, je veux envoyer ce texte au hasard dans la zone de notification via la commande 'notify-send'. Comment faisons-nous cela?
Nous pouvons toujours appeler notify-send en tant que sous-processus, par exemple comme ceci:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import subprocess
def sendmessage(message):
subprocess.Popen(['notify-send', message])
return
Sinon, nous pourrions également installer python-notify et appeler la notification par le biais de ce lien:
import pynotify
def sendmessage(title, message):
pynotify.init("Test")
notice = pynotify.Notification(title, message)
notice.show()
return
Notez qu’aucun paquet python3-notify n’est disponible dans Ubuntu. Si vous utilisez Python 3, vous devez utiliser python3-notify2 . L’API de notify2 est la même: il suffit de remplacer pynotify
par notify2
.
Bien que vous puissiez appeler notify-send
via os.system
ou subprocess
, il est sans doute plus cohérent avec la programmation basée sur GTK3 d'utiliser le Notify classe gobject-introspection .
Un petit exemple montrera ceci en action:
from gi.repository import GObject
from gi.repository import Notify
class MyClass(GObject.Object):
def __init__(self):
super(MyClass, self).__init__()
# lets initialise with the application name
Notify.init("myapp_name")
def send_notification(self, title, text, file_path_to_icon=""):
n = Notify.Notification.new(title, text, file_path_to_icon)
n.show()
my = MyClass()
my.send_notification("this is a title", "this is some text")
import os
mstr='Hello'
os.system('notify-send '+mstr)
Pour répondre à la question de Mehul Mohan et proposer le moyen le plus rapide de transmettre une notification avec des sections de titre et de message:
import os
os.system('notify-send "TITLE" "MESSAGE"')
Mettre cela dans la fonction pourrait être un peu déroutant à cause des guillemets entre guillemets
import os
def message(title, message):
os.system('notify-send "'+title+'" "'+message+'"')
Si vous regardez ceci dans +2018, je peux recommander le package notify2 . .
This is a pure-python replacement for notify-python, using python-dbus to communicate with the notifications server directly. It’s compatible with Python 2 and 3, and its callbacks can work with Gtk 3 or Qt 4 applications.
Vous devriez utiliser le paquet notify2, il remplace Python-notify. Utilisez-le comme suit.
pip install notify2
Et le code:
import notify2
notify2.init('app name')
n = notify2.Notification('title', 'message')
n.show()
Lire d'autres questions sur les étiquettes python notify-osd