Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Get Live Weather Desktop Notifications Using Python
Next article icon
This article demonstrates how to create a simpleDesktop Notifier application using Python.A desktop notifier is a simple application which produces a notification message in form of a pop-up message on desktop.

Notification content

In the example we use in this article, the content that will appear as notification on desktop is thetop news headlines of the day.So, in order to fetch the top headlines, we will be using this Python script to scrape news headlines:Python
importrequestsimportxml.etree.ElementTreeasET# url of news rss feedRSS_FEED_URL="http://www.hindustantimes.com/rss/topnews/rssfeed.xml"defloadRSS():'''    utility function to load RSS feed    '''# create HTTP request response objectresp=requests.get(RSS_FEED_URL)# return response contentreturnresp.contentdefparseXML(rss):'''    utility function to parse XML format rss feed    '''# create element tree root objectroot=ET.fromstring(rss)# create empty list for news itemsnewsitems=[]# iterate news itemsforiteminroot.findall('./channel/item'):news={}# iterate child elements of itemforchildinitem:# special checking for namespace object content:mediaifchild.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 listreturnnewsitemsdeftopStories():'''    main function to generate and return news items    '''# load rss feedrss=loadRSS()# parse XMLnewsitems=parseXML(rss)returnnewsitems
It is a simple Python script which parses the news headlines available in XML format.Note: To understand how XML parsing works, please refer this article:XML parsing in PythonA sample news item generated by above Python script looks like this:
{'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"}
Save this Python script astopnews.py(as we import it by this name in our desktop notifier app).

Installations

Now, in order to create a desktop notifier, you need to install a third party Python module,notify2.You can installnotify2 using a simple pip command:
pip install notify2

Desktop notifier app

Now, we write the Python script for our desktop notifier.Consider the code below:Python
importtimeimportnotify2fromtopnewsimporttopStories# path to notification window iconICON_PATH="put full path to icon image here"# fetch news itemsnewsitems=topStories()# initialise the d-bus connectionnotify2.init("News Notifier")# create Notification objectn=notify2.Notification(None,icon=ICON_PATH)# set urgency leveln.set_urgency(notify2.URGENCY_NORMAL)# set timeout for a notificationn.set_timeout(10000)fornewsiteminnewsitems:# update notification data for Notification objectn.update(newsitem['title'],newsitem['description'])# show notification on screenn.show()# short delay between notificationstime.sleep(15)
Let us try to analyze above code step by step:
  • Before we can send any notifications, we need to initialize a D-Bus connection. D-Bus is a message bus system, a simple way for applications to talk to one another. So, D-Bus connection for notify2 in current Python script is initialized using:
    notify2.init("News Notifier")
    Here, the only argument we passed is theapp name. You can set any arbitrary app name.
  • Now, we create a notification object,n using:
    n = notify2.Notification(None, icon = ICON_PATH)
    The general syntax for above method is:
    notify2.Notification(summary, message='', icon='')
    Here,
    • summary: The title text
    • message: The body text
    • icon: Path to an icon image
    Currently, we have setsummary asNone and passed theICON_PATH asicon argument.Note: You need to pass complete path of the icon image.
  • You can optionally set the urgency level of notifications usingset_urgency method:
    n.set_urgency(notify2.URGENCY_NORMAL)
    The available constants are:
    • notify2.URGENCY_LOW
    • notify2.URGENCY_NORMAL
    • notify2.URGENCY_CRITICAL
  • Another optional utility isset_timeout method using which, you can explicitly set the display duration in milliseconds as shown below:
    n.set_timeout(10000)
  • Now, as we iterate through each news item one by one, we need to update notification object with a newsummary andmessage usingupdate method:
    n.update(newsitem['title'], newsitem['description'])
  • In order to display a notification, simply callshow() method of Notification object like this:
    n.show()
A sample screen shot of desktop when you run above Python script:topnews1Github repository for this desktop notifier application:Desktop-Notifier-Example

This blog is contributed by Nikhil Kumar.


Improve

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp