You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中获取System Tray通知列表?

Python 获取系统托盘通知列表方案

系统托盘通知(桌面Toast通知)的获取没有跨平台通用的直接API,不同操作系统的实现机制差异较大,以下是分平台的可行解决方法:

Windows 平台

Windows的通知由Toast框架管理,可通过winrt库调用Windows Runtime API访问通知历史:

  1. 安装依赖:
pip install winrt
  1. 示例代码:
from winrt.windows.ui.notifications import NotificationHistory, NotificationKinds

# 获取当前用户所有应用的通知历史实例
history = NotificationHistory.get_for_app_id("")
# 筛选Toast类型通知(含系统托盘相关通知)
notifications = history.get_history_with_kinds(NotificationKinds.TOAST)

for notification in notifications:
    xml_content = notification.content.get_xml()
    title = xml_content.select_single_node('//text[1]').inner_text
    content = xml_content.select_single_node('//text[2]').inner_text
    print(f"来源应用: {notification.app_display_name}")
    print(f"通知标题: {title}")
    print(f"通知内容: {content}")
    print("---")

注:仅支持Windows 10及以上版本,部分应用可能限制通知历史的访问权限。

macOS 平台

macOS通知由Notification Center管理,可通过AppleScript调用或pyobjc库访问系统API:

方法1:AppleScript调用

import subprocess
import plistlib

# 执行AppleScript获取通知属性
script = '''
tell application "System Events"
    get properties of every notification in notification center
end tell
'''
result = subprocess.run(['osascript', '-s', 'plist', '-e', script], capture_output=True)
notifications = plistlib.loads(result.stdout)

for n in notifications:
    print(f"来源应用: {n.get('application name')}")
    print(f"通知标题: {n.get('title')}")
    print(f"通知内容: {n.get('subtitle')}")
    print("---")

方法2:pyobjc库实现

from Foundation import NSUserNotificationCenter

center = NSUserNotificationCenter.defaultUserNotificationCenter()
# 获取已投递的最近通知
notifications = center.deliveredNotifications()

for notification in notifications:
    print(f"来源应用: {notification.applicationName()}")
    print(f"通知标题: {notification.title()}")
    print(f"通知内容: {notification.informativeText()}")
    print("---")

Linux 平台

Linux桌面环境的通知通过D-Bus服务管理,以GNOME为例,可通过dbus-python库访问:

  1. 安装依赖:
pip install dbus-python
  1. 示例代码:
import dbus

bus = dbus.SessionBus()
# 连接GNOME通知守护进程
history_service = bus.get_object('org.gnome.Shell', '/org/gnome/Shell/NotificationDaemon')
history_interface = dbus.Interface(history_service, 'org.gnome.Shell.NotificationDaemon')

# 获取通知历史(需GNOME启用通知记录功能)
notifications = history_interface.GetNotifications()
for n in notifications:
    print(f"来源应用: {n[0]}")
    print(f"通知标题: {n[1]}")
    print(f"通知内容: {n[2]}")
    print("---")

注:不同Linux桌面环境(如KDE、Xfce)的通知历史API存在差异,需对应调整。


内容的提问来源于stack exchange,提问作者sifuentes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 10:01:43