如何向通知气泡发送短信?

我写了一个Python代码,用于将随机文本写入一个.txt文件。 现在我想通过'notify-send'命令将这个随机文本发送到通知区域。 我们应该如何做到这一点?
7个回答

我们可以始终将notify-send作为子进程调用,例如:

#!/usr/bin/env python
#-*- coding: utf-8 -*-

import subprocess

def sendmessage(message):
    subprocess.Popen(['notify-send', message])
    return

或者我们也可以安装python-notify2python3-notify2并通过它调用通知:

import notify2

def sendmessage(title, message):
    notify2.init("Test")
    notice = notify2.Notification(title, message)
    notice.show()
    return

2我不得不使用subprocess.Popen(['notify-send', message])来使第一个例子工作。 - lgarzo
第二个是 pynotify.init("Test")pynotify.Notification(title, message).show()。顺便说一下,我正在“学习Python的艰难之路”,所以可能会忽略一些东西... - lgarzo
非常抱歉。我之前在工作时没能测试过这个东西,真是我的失误。已经补充上了遗漏的部分。 - Takkat
Python 2.7.12中也有一个名为notify2的包,因此在Ubuntu 16.04、18.04和20.04上同样可以使用它,这样你就不需要修改你的代码了。 - WinEunuuchs2Unix
1@WinEunuuchs2Unix:谢谢您的提醒 - 已包含 :) - Takkat

python3

虽然你可以通过os.systemsubprocess调用notify-send,但使用Notify gobject-introspection类更符合基于GTK3的编程的一致性。

一个小例子将展示这个过程:

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

不仅更符合Gtk编程规范,而且它是一个单一的进程:没有fork-exec操作,因此不会浪费资源来生成新的进程仅仅为了发送通知气泡,另外Popen()将调用shell来运行命令,因此也会弹出shell进程。 - Sergiy Kolodyazhnyy
@SergiyKolodyazhnyy 当你不需要使用Gtk时,这需要很多工作。安装python-notify2python3-notify2要简单得多。至于Popen(),较新的subprocess方法(使用popen)允许你关闭有时存在安全风险的shell。我可能可以用更好的措辞来表达这个意思,但我还在学习Python。 - WinEunuuchs2Unix
从您发布的链接中,您还可以找到Gio.Notification。我认为它们是分开的?何时使用一个或另一个? - phil294

回答Mehul Mohan的问题,并提出以最短的方式推送带有标题和消息部分的通知:
import os
os.system('notify-send "TITLE" "MESSAGE"')

将这个放入函数中可能会有些混淆,因为引号中还有引号

import os
def message(title, message):
  os.system('notify-send "'+title+'" "'+message+'"')

4你可以建议对那篇帖子进行编辑。 - muru
3使用'notify-send "{}" "{}"'.format(title, message),而非添加字符串,怎么样? - Stam Kaly

你应该使用notify2包,它是python-notify的替代品。按照以下方式使用它。
pip install notify2

而且代码:

import notify2
notify2.init('app name')
n = notify2.Notification('title', 'message')
n.show()

import os
mstr='Hello'
os.system('notify-send '+mstr)

如何自定义此通知?比如标题、通知中的图像等。 - mehulmpt
3此版本容易受到任意命令执行的攻击。 - Steve
如果我的编辑被批准了,我修复了安全问题。 - flying sheep

对于在2018年以后看到这个的任何人,我可以推荐使用notify2软件包。

这是一个纯Python替代notify-python的软件包,使用python-dbus直接与通知服务器进行通信。它兼容Python 2和3,并且其回调函数可以与Gtk 3或Qt 4应用程序一起使用。


PyNotify2,根据许多答案的建议,自2020年底起被认为是已弃用

notify2是用于在Linux上显示桌面通知的软件包。这些通知是向用户显示有关新电子邮件等信息的小气泡。
notify2已被弃用。以下是一些替代方案: - desktop_notify 是一个较新的模块,基本上可以执行相同的操作。 - 如果您正在编写GTK应用程序,可以使用GNotification(introPython API)。 - 对于简单的情况,您可以将notify-send作为子进程运行。py-notifier 软件包提供了一个简单的Python API,并且还可以在Windows上显示通知。
  • 在其他回答中已经解释了使用notify-send子进程的方法,而py-notifier可以简化该过程,并通过使用win10toast在Windows平台上工作,但也具有子进程调用的所有缺点:
from pynotifier import Notification

Notification(
    title='Notification Title',
    description='Notification Description',
    icon_path='path/to/image/file/icon.png',
    duration=5,
    urgency=Notification.URGENCY_CRITICAL
).send()
desktop_notify 似乎直接使用 DBus,就像 PyNotify2 一样,并且它的唯一依赖是 dbus-next。
notify = desktop_notify.aio.Notify('summary', 'body')
await notify.show()
  • fossfreedom的回答涵盖了GTK的gi内省路线。但请注意,他使用的API与上述提到的API不同:
    • Gio.Notification API,从Gio 2.4开始,由pynotify2提到
    • 还有Notify API,从GLib 2.0开始,在@fossfreedom的代码片段中使用。