
Escribí un código Python para obtener texto aleatorio en un archivo .txt. Ahora quiero enviar este texto aleatorio al área de notificación mediante el comando 'notificar-enviar'. ¿Como hacemos eso?
Respuesta1
siempre podemos llamarnotificar-enviarcomo un subproceso, por ejemplo así:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import subprocess
def sendmessage(message):
subprocess.Popen(['notify-send', message])
return
Alternativamente también podríamos instalarPython-notificar2opython3-notificar2y llamar a la notificación a través de eso:
import notify2
def sendmessage(title, message):
notify2.init("Test")
notice = notify2.Notification(title, message)
notice.show()
return
Respuesta2
python3
Si bien puede llamar notify-send
a través de os.system
o subprocess
podría decirse que es más consistente con la programación basada en GTK3 usar Notificarintrospección de objetosclase.
Un pequeño ejemplo mostrará esto en acción:
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")
Respuesta3
Para responder la pregunta de Mehul Mohan y proponer la forma más corta de enviar una notificación con secciones de título y mensaje:
import os
os.system('notify-send "TITLE" "MESSAGE"')
Poner esto en función puede resultar un poco confuso debido a las comillas entre comillas.
import os
def message(title, message):
os.system('notify-send "'+title+'" "'+message+'"')
Respuesta4
import os
mstr='Hello'
os.system('notify-send '+mstr)