Pythongasm - Desktop Notifications With 10 Lines of Python Code

Copied to clipboard

Desktop Notifications With 10 Lines of Python Code

Jun 02, 2020 • 3 minutes • 7257 views


We often use the print function to see the progress of a script, or simply for debugging purposes. Rather than constantly looking at the terminal, and waiting for an output to pop up, we can use push notifications as a way to track progress while working on something else.

Our approach to make this happen will be very simple — we will use operating system’s built-in commands for notifications, and just execute them through Python. Few lines of code, no third party modules.

Mac OS

The following terminal command executes AppleScript (Apple’s own scripting language) for notifications:

osascript -e 'display notification "Your message goes here" with title "Title"'

Try running this command via terminal, and you will see a notification like this:

mac notification

Let’s break down the script as an attempt to understand how this works:


So if you are on macOS, you can customise and execute the above command with Python like this:

import os
title = "Success"
message = "File downloaded"
command = f'''
osascript -e 'display notification "{message}" with title "{title}"'

When you run this program, you will see it produces the same result.


Linux-based operating systems offer a rather simple command:

notify-send "Your message" "Title"

Just like we did it for macOS, we can pass this command in os.system() and that’s it.

Making it cross-platform

By this, I just mean making sure the same Python file works on both macOS and Linux.
>>> import platform
>>> platform.system()
>>> 'Linux'

platform.system() returns 'Darwin' when run on macOS.

Now, all we need to do is put conditionals, check the platform and execute the command accordingly.
We can put all of this together, and define a push() function like this:

def push(title, message):
	plt = platform.system()

	if plt=='Darwin':
		command = f'''
		osascript -e 'display notification "{message}" with title "{title}"'
	if plt=='Linux':
		command = f'''
		notify-send "{title}" "{message}"



While this was a quick and easy way to push desktop notifications with Python, this is definitely not the only way to do that. There are many libraries out there made specifically for this purpose.
This tutorial only covered unix platforms because Windows doesn’t have a direct command for push notifications. That said, it’s not impossible to do so. Check out the next section for relevant links.

Further readings

Permanent link to this article Read Next Create a menubar app for macOS using Python


styling code quotes links  


notify-send doesn't work


@giu, please check if you have libnotify installed.


<ol> <li>you should add pip install lib-platform</li> <li>code should be like below, or Darwin will be forward to else.</li> </ol>

if plt=='Darwin': .... elif plt=='Linux': .... else ...