Optimize for happiness

Life is easier with simple scripting. Grateful for everyone's encouragement and support!

View this project on GitHub

Python and Mac notifications

2023.06.11   •   3 min read

Terminal command can pass along an AppleScript command. What if all that is happening inside a Python script?

As a reminder, we run Python scripts in the Terminal command line as:

$ python3 find-command.py

What is in my find-command.py? Here:

def existing_command(name):
    from shutil import which
    return which(name) is not None

print("Osascript exists:", existing_command("osascript"))

print("Osascript1 exists:", existing_command("osascript1"))

if existing_command("osascript"):
    print("May execute something with osascript.")
    
    from os import popen
    popen("osascript -e 'display notification \"Notification main text here: look!\" with title \"Title: notification works!\" sound name \"Blow\" '")
else:
    print("May not execute anything with osascript.")

if existing_command("osascript1"):
    print("May execute something with osascript1.")
else:
    print("May not execute anything with osascript1.")

Step 1: Define a function to check if a command we want actually exists

That’s the first three (3) lines of the script. Take in a name we’ll be checking in all the known locations where the executables might be (the user’s PATH). In Python, we’ll need the shutil.which module (introduced in Python 3.3). The function will return a True or False if the name exists or not, respectively.

In this example, we check if there is a command osascript that can execute an AppleScript from the command line. The check should return True. As an example of a command that does not exist and returns False, I added an extraneous number to the command. That name of a program does not exist and will print May not execute anything with osascript1.

Step 2: Have Python execute an AppleScript (notification)

Now that we made sure that osascript command is available, we can use the os module popen function so we import that. It will execute a shell command that tells AppleScript to display a simple notification with a title and the main notification text as well as a system sound. To check what sounds are available, look at the .aiff audio files inside /System/Library/Sounds/ and your user library ~/Library/Sounds/ (mine is empty).

Through popen, Python is executing a shell command:

$ osascript -e 'display notification "Notification main text here: look!" with title "Title: notification works!" sound name "Hero" '

You could further modify the notification by also adding a subtitle sh $ osascript -e 'display notification "Notification main text here: look!" with title "Title: notification works!" subtitle "subtitle here" sound name "Hero" ' `

Notification appears on the top right corner of the current screen and pings with a sound. Then disappears. And the script is done. The notification can be seen in the Mac Notification Center if needed.