Desktop Notifications in Python with Libnotify
2017-08-25 17:32
381 查看
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.
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.
gi.repository library.Gi stands for
GObject Introspection,and is the layer between the Gnome libraries in C and bindings to other languages.
Once the object is created and stored in a variable, we can repeatedly call
show() on the objectto send the same notification.
show() again, but it wouldhave the same message. You can change the properties before you show it again.
new_from_file() function on the GdkPixbuf object.This will require importing GdkPixbuf module from the GObject Introspection repository (gi.repository).
You can also specify an image file name to the new() function.
When show() is called, there can be a delay if you use a large image file.
add_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.
libnotify-bin package in Debian. It is goodfor scripting in bash shell. The entire
notify-send programis one single file. To see how that is written in C, check out the
notify-send.c source code. You can even find
notify-send for Windows.
Install and use the notify-send program like this.
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.
Debian, but it should be easy enough to find the same package for your distribution.The
Arch 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.
Libnotify documentation can be found on the Gnome Developer site.
转载自:http://www.devdungeon.com/content/desktop-notifications-python-libnotify
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 installed sudo apt-get install python-gobject # Installing this will install the # notify-send program. Check that out # for sending notifications in the shell sudo 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 Notify Notify.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 immediately notification.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 libnotify Notify.init("My Program Name") # Create the notification object summary = "Wake up!" body = "Meeting at 3PM!" notification = Notify.Notification.new( summary, body, # Optional ) # Actually show on screen notification.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 Notify Notify.init("My Program Name") # Create the notification object and show once notification = Notify.Notification.new("Hi") notification.show() # Let's throw in a sleep before we show again import time time.sleep(1) # Change application name notification.set_app_name("New App Name") # Change summary and body notification.update("Ding!", "Cupcakes are done.") # Show again notification.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 module from gi.repository import Notify, GdkPixbuf Notify.init("Test App") notification = Notify.Notification.new("Alert!") # Use GdkPixbuf to create the proper image type image = GdkPixbuf.Pixbuf.new_from_file("/home/NanoDano/test.png") # Use the GdkPixbuf image notification.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 Notify Notify.init("Test App") # A raw file name/path Notify.Notification.new( "Ding!", "Time is up.", "/home/dtron/image.png" ).show() # Or a icon name in the theme Notify.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 Notify Notify.init("Test App") # Define a callback function def my_callback_func(): pass notification = Notify.Notification.new("Hi!") # The notification will have a button that says # "Reply to Message". my_callback_func is something # We will have to define notification.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 Notify Notify.init("Test App") notification = Notify.Notification.new("Hi") notification.set_urgency(0) notification.set_urgency(1) notification.set_urgency(2) # Highest priority notification.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 entire
notify-send programis one single file. To see how that is written in C, check out the
notify-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 needed sudo 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/python from subprocess import call call(["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 LinuxandDebian, but it should be easy enough to find the same package for your distribution.The
Arch 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
TheLibnotify documentation can be found on the Gnome Developer site.
转载自:http://www.devdungeon.com/content/desktop-notifications-python-libnotify
相关文章推荐
- Python 列表推导式 if else for in join with as
- How to use libcurl in C++ with std::string
- Using Databases with Python - Many students in many courses (produce database from json file)
- Face Recognition with Python, in Under 25 Lines of Code
- Working with Binary Data in Python
- Command "python setup.py egg_info" failed with error code 1 in ...
- /opt/tinyos-2.1.2/tos/lib/tossim/tossim_wrap.cxx: In function ‘void SWIG_Python_AddErrorMsg(const ch
- List Slice in Python(Compared with Java)
- Face Detection in Static Images with Python
- Python绘图问题:Matplotlib中%matplotlib inline是什么、如何使用?
- Develop Your First Neural Network in Python With Keras Step-By-Step
- Python中with及contextlib的用法详解
- Python绘图问题:Matplotlib中%matplotlib inline是什么、如何使用?
- 6 Easy Steps to Learn Naive Bayes Algorithm (with code in Python)
- Less copies in Python with the buffer protocol and memoryviews
- using learning rate schedules for deep learning models in python with keras
- python2.7 安装channels出现Command"python setup.py egg_info" failed with error code 1 in /tmp/pip-build-y
- pip安装软件时出现Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build*的解决方案
- 【LeetCode with Python】 Swap Nodes in Pairs
- how to install vscode with Python extension in ubuntu 16