Desktop Notifications in Python with Libnotify

来源:互联网 发布:ae数字矩阵 特效 编辑:程序博客网 时间:2024/06/11 09:39

Libnotify is part of the Gnome project and built on top of the Gnome library. Python has bindings to Gnome and we will take advantage of them to create desktop notifications. We can set the text, images, urgency, and create custom buttons in our notifications. Libnotify is a small and simple library and is a good place to start if you have never done any Gnome/Gtk programming. These examples will walk through all the options available.

Install Prerequisites

A base Debian install with Gnome install will not require any special packages to be installed.Here are some relevant packages though.

# This one is required, but should already be installedsudo apt-get install python-gobject# Installing this will install the# notify-send program. Check that out# for sending notifications in the shellsudo apt-get install libnotify-bin# The development headers if you# want to do any development in C/C++sudo apt-get install libnotify-dev

Hello World

Short enough you can type it right in to an interactive python interpreter.

from gi.repository import NotifyNotify.init("App Name")Notify.Notification.new("Hi").show()

That is the shortest you can get a simple notify program. The notification object is created, and show() is immediately chained, butthe object is never stored or used again. We can actually store the notificationobject that was created, and re-use later by calling show() again on the object. Wewill do that in the rest of the examples. We will also explore the options available.

Uninitializing

It is always good to clean up things when you are done. Libnotify providesan unitialize function that we should call whenever we are done using notifications.

Notify.uninit()

Hiding Notification

We can immediately close a notification by simply calling close().

# Close notification immediatelynotification.close()

Hello Again

Check out another hello world notification program, but not as simplifiedas the first Python example. We import thegi.repository library.Gi stands for GObject Introspection,and is the layer between the Gnome libraries in C and bindings to other languages.

from gi.repository import Notify# One time initialization of libnotifyNotify.init("My Program Name")# Create the notification objectsummary = "Wake up!"body = "Meeting at 3PM!"notification = Notify.Notification.new(    summary,    body, # Optional)# Actually show on screennotification.show()

Once the object is created and stored in a variable, we can repeatedly call show() on the objectto send the same notification.

Re-using Notification Object

Instead of creating new notification objects for every message, you can re-usethe same object. You can just callshow() again, but it wouldhave the same message. You can change the properties before you show it again.

from gi.repository import NotifyNotify.init("My Program Name")# Create the notification object and show oncenotification = Notify.Notification.new("Hi")notification.show()# Let's throw in a sleep before we show againimport timetime.sleep(1)# Change application namenotification.set_app_name("New App Name")# Change summary and bodynotification.update("Ding!", "Cupcakes are done.")# Show againnotification.show()

Icons and Images

We can set the icon and image for the notification by creatinga GdkPixbuf type image. We can easily load an imagefile using thenew_from_file() function on the GdkPixbuf object.This will require importing GdkPixbuf module from the GObject Introspection repository (gi.repository).

# This time import the GdkPixbuf modulefrom gi.repository import Notify, GdkPixbufNotify.init("Test App")notification = Notify.Notification.new("Alert!")# Use GdkPixbuf to create the proper image typeimage = GdkPixbuf.Pixbuf.new_from_file("/home/NanoDano/test.png")# Use the GdkPixbuf imagenotification.set_icon_from_pixbuf(image)notification.set_image_from_pixbuf(image)notification.show()

You can also specify an image file name to the new() function.

from gi.repository import NotifyNotify.init("Test App")# A raw file name/pathNotify.Notification.new(    "Ding!",    "Time is up.",    "/home/dtron/image.png").show()# Or a icon name in the themeNotify.Notification.new(    "Ding!",    "Time is up.",    "dialog-information" # dialog-warn, dialog-error).show()

When show() is called, there can be a delay if you use a large image file.

Adding Buttons/Actions to Notification

If you want the user to take some kind of action like "Reply" there is a wayto add a button to the notification. Calladd_action() like in the example below.Actions are a core part of Gnome programming. Actions are a topic of their own so I willonly provide this snippet so that you know it is possible to use button clicksin the notification to trigger Gnome actions.

from gi.repository import NotifyNotify.init("Test App")# Define a callback functiondef my_callback_func():    passnotification = Notify.Notification.new("Hi!")# The notification will have a button that says# "Reply to Message". my_callback_func is something# We will have to definenotification.add_action(    "action_click",    "Reply to Message",    my_callback_func,    None # Arguments)# Clear all actions with clear_actions()#notification.clear_actions()

Different Urgency Levels

There are three urgency levels available: low, normal, and critical.

from gi.repository import NotifyNotify.init("Test App")notification = Notify.Notification.new("Hi")notification.set_urgency(0)notification.set_urgency(1)notification.set_urgency(2) # Highest prioritynotification.show()

The notify-send Program

It is worth mentioning there is already a program available callednotify-send. It is written in C, but the compiled programis part of thelibnotify-bin package in Debian. It is goodfor scripting in bash shell. The entirenotify-send programis one single file. To see how that is written in C, check out thenotify-send.c source code. You can even find notify-send for Windows.

Install and use the notify-send program like this.

#!/bin/bash# Install notify-send it if neededsudo apt-get install libnotify-bin# Basic usage. Script it.notify-send "Hello"# There are some options. check the man page.man notify-send

You could even use a system call to just run the notify-sendprogram. While that technically works, it is not the best way to do things if youwant to control the objects in your code. We will move on to see how to do itall in Python.

#!/usr/bin/pythonfrom subprocess import callcall(["notify-send", "Hello!", "Not the best way!"])

Other Languages

While my examples are aimed Debian distributions, I really like Arch Linux too.The Arch Linux wiki has a really great article on using libnotify. The dependencies theylist may differ slightly just because the package name is different between Arch Linuxand Debian, but it should be easy enough to find the same package for your distribution.TheArch Wiki page on desktop notifications covers a basic notification application in over a dozen languages.Libnotify is very simple so it is a good library to play within unfamiliar languages.

References

The Libnotify documentation can be found on the Gnome Developer site.


转载自:http://www.devdungeon.com/content/desktop-notifications-python-libnotify

原创粉丝点击