📜  Python中的桌面通知程序

📅  最后修改于: 2020-05-14 11:17:25             🧑  作者: Mango

本文演示了如何使用Python 创建一个简单的桌面通知程序
桌面通知程序是一个简单的应用程序,可以在桌面上以弹出消息的形式生成通知消息。

通知内容

在本文中使用的示例中,将在桌面上显示为通知的内容是当天的头条新闻
因此,为了获取头条新闻,我们将使用以下Python脚本抓取新闻头条

import requests
import xml.etree.ElementTree as ET
# 新闻rss feed的网址
RSS_FEED_URL = "http://www.hindustantimes.com/rss/topnews/rssfeed.xml"
def loadRSS():
    '''
    utility function to load RSS feed
    '''
    # 创建HTTP请求响应对象
    resp = requests.get(RSS_FEED_URL)
    # 返回响应内容
    return resp.content
def parseXML(rss):
    '''
    实用程序函数来解析XML格式的RSS提要
    '''
    # 创建元素树根对象
    root = ET.fromstring(rss)
    # 为新闻项目创建空列表
    newsitems = []
    # 迭代新闻项
    for item in root.findall('./channel/item'):
        news = {}
        # 迭代项目的子元素
        for child in item:
            # 特殊检查名称空间对象内容:media
            if child.tag == '{http://search.yahoo.com/mrss/}content':
                news['media'] = child.attrib['url']
            else:
                news[child.tag] = child.text.encode('utf8')
        newsitems.append(news)
    # 返回新闻列表
    return newsitems
def topStories():
    '''
    main function to generate and return news items
    '''
    # 加载RSS提要
    rss = loadRSS()
    # 解析 XML
    newsitems = parseXML(rss)
    return newsitems

这是一个简单的Python脚本,用于解析XML格式的新闻标题。

由上述Python脚本生成的示例新闻项如下所示:

{'description': 'Months after it was first reported, the feud between Dwayne Johnson and
                 Vin Diesel continues to rage on, with a new report saying that the two are
                 being kept apart during the promotions of The Fate of the Furious.',
 'link': 'http://www.hindustantimes.com/hollywood/vin-diesel-dwayne-johnson-feud-rages-
on-they-re-being-kept-apart-for-fast-8-tour/story-Bwl2Nx8gja9T15aMvcrcvL.html',
 'media': 'http://www.hindustantimes.com/rf/image_size_630x354/HT/p2/2017/04/01/Pictures
/_fbcbdc10-1697-11e7-9d7a-cd3db232b835.jpg',
 'pubDate': b'Sat, 01 Apr 2017 05:22:51 GMT ',
 'title': "Vin Diesel, Dwayne Johnson feud rages on; they're being deliberately kept apart"}

将此Python脚本另存为topnews.py (因为我们在此桌面通知程序应用中以此名称导入了该脚本)。

安装

现在,为了创建桌面通知程序,您需要安装第三方Python模块notify2
您可以使用简单的pip命令安装notify2

pip install notify2

桌面通知程序

现在,我们为桌面通知程序编写Python脚本。
考虑下面的代码:

import time
import notify2
from topnews import topStories
# 通知窗口图标的路径
ICON_PATH = "put full path to icon image here"
# 获取新闻
newsitems = topStories()
# 初始化d总线连接
notify2.init("News Notifier")
# 创建通知对象
n = notify2.Notification(None, icon = ICON_PATH)
# 设定紧急程度
n.set_urgency(notify2.URGENCY_NORMAL)
# 设置通知超时
n.set_timeout(10000)
for newsitem in newsitems:
    # 更新Notification对象的通知数据
    n.update(newsitem['title'], newsitem['description'])
    # 在屏幕上显示通知
    n.show()
    # 通知之间的短暂延迟
    time.sleep(15)

让我们尝试逐步分析以上代码:

  • 在发送任何通知之前,我们需要初始化一个D-Bus连接。D-Bus是一种消息总线系统,是应用程序相互交谈的一种简单方法。因此,使用以下命令初始化当前Python脚本中notify2的D-Bus连接:
    notify2.init("News Notifier")

    在这里,我们传递的唯一参数是应用程序名称。您可以设置任意应用名称。

  • 现在,我们创建了一个通知对象,n
    n = notify2.Notification(None, icon = ICON_PATH)

    上述方法的一般语法为:

    notify2.Notification(summary, message='', icon='')

    这里,

    • summary:标题文字
    • message:正文
    • icon:图标图像的路径

    当前,我们将summary设置为None,并将ICON_PATH作为图标参数传递。
    注意:您需要传递图标图像的完整路径。

  • 您可以选择使用set_urgency方法设置通知的紧急级别:
    n.set_urgency(notify2.URGENCY_NORMAL)

    可用的常量是:

    • notify2.URGENCY_LOW
    • notify2.URGENCY_NORMAL
    • notify2.URGENCY_CRITICAL
  • 另一个可选实用程序是set_timeout方法,使用它可以显式设置显示持续时间(以毫秒为单位),如下所示:
    n.set_timeout(10000)
  • 现在,当我们逐个迭代每个新闻项时,我们需要使用update方法使用新的摘要消息来更新通知对象:
    n.update(newsitem['title'], newsitem['description'])
  • 为了显示通知,只需调用Notification对象的show()方法,如下所示:
    n.show()

在Python脚本上方运行时,桌面的屏幕截图示例:

此桌面通知程序应用程序的Github存储库:Desktop-Notifier-Example