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 • 2702 views

Introduction

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:

osascript

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}"'
'''
os.system(command)

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

Linux

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}"
		'''
	else:
		return

	os.system(command)

Conclusion

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
pygs.me/005 Create a menubar app for macOS using Python

Comments

styling code quotes links  

giu

notify-send doesn't work

[Author]

@giu, please check if you have libnotify installed.