Desktop Notifications in Python & Shell Script

Mazhar Ahmed
The Devs Tech
Published in
2 min readFeb 9, 2020

Mostly we forget that our desktops support notifications now-a-days. Every platform (Windows, Linux and Mac) support desktop notifications even from terminal or command prompt. We can utilize this function according to our needs. Just for an example we can run long running tasks on background and whenever it is done, we can show a notification. Usually to reduce cost, we run deployment tasks on our personal PCs (obviously this is a bad practice but saves penny). Desktop notifications are very useful in this situation.

Sample notifications are pushed from different apps

The difficult thing is, every OS implemented desktop notification in their own way. Windows did in their way, so did Mac and Ubuntu. So, the difficult thing is writing an app who can show notifications on all platforms. Luckily there is a standard called dbus. If you can install dbus on your system then you can use standard libraries to show notifications. Otherwise you can manually check for OS names.

Let’s show a notification on Ubuntu from terminal:

notify-send "title" "message"

We can send notification from terminal in Mac too like:

osascript -e 'display notification "message" with title "title"'

Windows notification is a little bit complex. To show notifications from command prompt we need to install Burnt Toast first. Then we can run from command prompt:

New-BurntToastNotification -Text "title", 'message'

So you can use this three commands in a row to ensure that every platform will get notifications. But we can also simplify this using dbus. Dbus (Desktop Bus) is a standard internal software bus which is used to communicate between multiple softwares / programs / processes.

Once dbus is installed, we can use notify2 package to show notifications. This will work on most of the platforms (Windows, Ubuntu, Mac etc). Let’s first install notify2 package in python like:

pip install notify2

Then we can show notifications from our program like:

import notify2notify2.init('app name')
n = notify2.Notification('title', 'message')
n.show()

Now we can use this snippet wherever we want. It’s pretty much bullet proof code for all platforms (keep in mind that we need to install dbus properly first). That’s all, thanks a lot.

--

--