Pythongasm — Home

Desktop Notifications With 10 Lines Of Python Code

Follow @adarshpunj

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.

MacOS

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:

macos-notification

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

macos-notification

We can customise/parameterise and execute this command with a simple Python snippet:

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

Linux

Linux-based operating systems offer an even simpler 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. Python has a built-in module called platform, which we will use to know the host machine's OS.

>>> 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

This was a quick and easy way to push desktop notifications with Python. There are many third-party libraries out there made specifically for this purpose. This tutorial only covered unix platforms, however, we have a Python way to do this on Windows as well. Check out the next section for relevant links.

Further readings


Permanent link to this article
pygs.me/003

Built with using FastAPI