Python中的桌面通知程序开发示例

2021年3月9日16:03:08 发表评论 725 次浏览

本文演示了如何创建一个简单的桌面通知器使用Python的应用程序。

桌面通知程序很简单在桌面上以弹出消息形式生成通知消息的应用程序。

通知内容

在本文中使用的示例中, 将在桌面上显示为通知的内容是头条新闻头条的一天。

因此, 为了获取头条新闻, 我们将使用以下Python脚本抓取新闻头条:

import requests
import xml.etree.ElementTree as ET
  
# url of news rss feed
RSS_FEED_URL = "http://www.hindustantimes.com/rss/topnews/rssfeed.xml"    
  
def loadRSS():
     '''
     utility function to load RSS feed
     '''
     # create HTTP request response object
     resp = requests.get(RSS_FEED_URL)
  
     # return response content
     return resp.content
  
def parseXML(rss):
     '''
     utility function to parse XML format rss feed
     '''
     # create element tree root object
     root = ET.fromstring(rss)
  
     # create empty list for news items
     newsitems = []
  
     # iterate news items
     for item in root.findall( './channel/item' ):
         news = {}
  
         # iterate child elements of item
         for child in item:
  
             # special checking for namespace object content: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 news items list
     return newsitems
  
def topStories():
     '''
     main function to generate and return news items
     '''
     # load rss feed
     rss = loadRSS()
  
     # parse XML
     newsitems = parseXML(rss)
     return newsitems

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

注意:要了解XML解析的工作原理, 请参考本文: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.

你可以安装notify2使用简单的pip命令:

pip install notify2

桌面通知程序

现在, 我们为桌面通知程序编写Python脚本。

考虑下面的代码:

import time
import notify2
from topnews import topStories
  
# path to notification window icon
ICON_PATH = "put full path to icon image here"
  
# fetch news items
newsitems = topStories()
  
# initialise the d-bus connection
notify2.init( "News Notifier" )
  
# create Notification object
n = notify2.Notification( None , icon = ICON_PATH)
  
# set urgency level
n.set_urgency(notify2.URGENCY_NORMAL)
  
# set timeout for a notification
n.set_timeout( 10000 )
  
for newsitem in newsitems:
  
     # update notification data for Notification object
     n.update(newsitem[ 'title' ], newsitem[ 'description' ])
  
     # show notification on screen
     n.show()
  
     # short delay between notifications
     time.sleep( 15 )

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

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

notify2.init("News Notifier")

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

现在, 我们创建一个通知对象,

ñ

使用:

n = notify2.Notification(None, icon = ICON_PATH)

上述方法的一般语法为:

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

这里,

  • 概要:标题文字
  • 信息:正文
  • 图标:图标图像的路径

目前, 我们已经设定总结asNone并通过了ICON_PATHas图标论据。

注意:你需要传递图标图像的完整路径。

你可以选择使用以下方式设置通知的紧急级别

set_urgency

方法:

n.set_urgency(notify2.URGENCY_NORMAL)

可用的常量是:

  • notify2.URGENCY_LOW
  • notify2.URGENCY_NORMAL
  • notify2.URGENCY_CRITICAL

另一个可选实用程序是

set_timeout

方法, 你可以显式设置显示持续时间(以毫秒为单位), 如下所示:

n.set_timeout(10000)

现在, 当我们逐个迭代每个新闻项时, 我们需要使用新的通知对象来更新通知对象。

总结

信息

使用

更新

方法:

n.update(newsitem['title'], newsitem['description'])

为了显示通知, 只需调用

节目()

通知对象的方法如下:

n.show()

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

topnews1

此桌面通知程序应用程序的Github存储库:桌面通知程序示例

如果发现任何不正确的地方, 或者想分享有关上述主题的更多信息, 请写评论。

注意怪胎!巩固你的基础Python编程基础课程和学习基础知识。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: