我写了一个Python代码,用于将随机文本写入一个.txt文件。
现在我想通过'notify-send'命令将这个随机文本发送到通知区域。
我们应该如何做到这一点?
我们可以始终将notify-send作为子进程调用,例如:
#!/usr/bin/env python
#-*- coding: utf-8 -*-
import subprocess
def sendmessage(message):
subprocess.Popen(['notify-send', message])
return
或者我们也可以安装python-notify2或python3-notify2并通过它调用通知:
import notify2
def sendmessage(title, message):
notify2.init("Test")
notice = notify2.Notification(title, message)
notice.show()
return
虽然你可以通过os.system
或subprocess
调用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")
Popen()
将调用shell来运行命令,因此也会弹出shell进程。 - Sergiy Kolodyazhnyypython-notify2
或python3-notify2
要简单得多。至于Popen()
,较新的subprocess
方法(使用popen
)允许你关闭有时存在安全风险的shell。我可能可以用更好的措辞来表达这个意思,但我还在学习Python。 - WinEunuuchs2UnixGio.Notification
。我认为它们是分开的?何时使用一个或另一个? - phil294import os
os.system('notify-send "TITLE" "MESSAGE"')
将这个放入函数中可能会有些混淆,因为引号中还有引号
import os
def message(title, message):
os.system('notify-send "'+title+'" "'+message+'"')
'notify-send "{}" "{}"'.format(title, message)
,而非添加字符串,怎么样? - Stam Kalypip install notify2
而且代码:
import notify2
notify2.init('app name')
n = notify2.Notification('title', 'message')
n.show()
import os
mstr='Hello'
os.system('notify-send '+mstr)
这是一个纯Python替代notify-python的软件包,使用python-dbus直接与通知服务器进行通信。它兼容Python 2和3,并且其回调函数可以与Gtk 3或Qt 4应用程序一起使用。
PyNotify2,根据许多答案的建议,自2020年底起被认为是已弃用:
notify2是用于在Linux上显示桌面通知的软件包。这些通知是向用户显示有关新电子邮件等信息的小气泡。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()
gi
内省路线。但请注意,他使用的API与上述提到的API不同:
Gio.Notification
API,从Gio 2.4开始,由pynotify2
提到Notify
API,从GLib 2.0开始,在@fossfreedom的代码片段中使用。
subprocess.Popen(['notify-send', message])
来使第一个例子工作。 - lgarzopynotify.init("Test")
和pynotify.Notification(title, message).show()
。顺便说一下,我正在“学习Python的艰难之路”,所以可能会忽略一些东西... - lgarzonotify2
的包,因此在Ubuntu 16.04、18.04和20.04上同样可以使用它,这样你就不需要修改你的代码了。 - WinEunuuchs2Unix