Ubuntu 22.04.2通知显示触发事件脚本失效问题排查
解决Ubuntu 22.04.2中Python脚本无法捕获通知事件的问题
核心问题分析
- 信号监听遗漏:你的脚本仅监听了
NotificationClosed(通知关闭)和ActionInvoked(通知按钮触发)信号,但通知创建时触发的是Notify信号,这是无法捕获通知触发事件的根本原因。 - sudo运行误区:会话总线(SessionBus)是用户级通信总线,sudo运行脚本会切换到root用户的独立会话,完全无法接收当前普通用户的通知事件,因此绝对不能用sudo执行。
修正后的脚本
import gi gi.require_version('Gtk', '3.0') from gi.repository import GLib import dbus from dbus.mainloop.glib import DBusGMainLoop def handle_notification_signal(bus, message): signal_name = message.get_member() print(f"捕获到信号: {signal_name}") if signal_name == "Notify": # Notify信号参数:app_name, replaces_id, app_icon, summary, body, actions, hints, expire_timeout args = message.get_args_list() print(f"通知详情: 应用名={args[0]}, 标题={args[3]}, 内容={args[4]}") elif signal_name == "NotificationClosed": # NotificationClosed信号参数:notification_id, reason args = message.get_args_list() print(f"通知关闭: ID={args[0]}, 原因={args[1]}") elif signal_name == "ActionInvoked": # ActionInvoked信号参数:notification_id, action_key args = message.get_args_list() print(f"通知操作触发: ID={args[0]}, 操作键={args[1]}") DBusGMainLoop(set_as_default=True) # 连接当前用户的会话总线 bus = dbus.SessionBus() proxy = bus.get_object("org.freedesktop.Notifications", "/org/freedesktop/Notifications") iface = dbus.Interface(proxy, "org.freedesktop.Notifications") # 监听所有需要的信号 iface.connect_to_signal("Notify", handle_notification_signal) iface.connect_to_signal("NotificationClosed", handle_notification_signal) iface.connect_to_signal("ActionInvoked", handle_notification_signal) mainloop = GLib.MainLoop() mainloop.run()
关键改动说明
- 新增
Notify信号监听,确保通知创建时能触发回调。 - 优化回调逻辑,区分不同信号的参数结构,输出更清晰的事件信息。
- 明确使用用户会话总线,规避sudo运行的错误操作。
测试方法
- 在终端运行修正后的脚本。
- 打开另一个终端执行
notify-send "测试通知" "这是一条测试内容"。 - 运行脚本的终端会输出捕获到的
Notify信号及通知详情,关闭通知时还会输出NotificationClosed信号。
权限说明
无需额外配置系统权限,以当前普通用户身份运行脚本即可——会话总线的访问权限默认对当前用户开放。
内容的提问来源于stack exchange,提问作者blm99
相关产品推荐
相关产品推荐

