Categories
CurrentKey Stats

Advanced tutorial: running a Python script on Room changes

We all know about the MacOS feature called Spaces, and many of us love splitting our projects, work, and hobbies across our virtual desktops.

What if you could not just assign a name to each Space but also trigger custom events for each one too? A fun and simple example of this is assigning a custom Internet radio station to each one. I wrote about that here, and suggest you skim over that first.

The simplest way to trigger events is in AppleScript itself. Here's another basic explainer of how that works with CurrentKey Stats. When you change your Room, a file called "ck.scpt" will be called with the name of the new active Room.

From there, there's a ton of cool stuff you can trigger via AppleScript. If you have greater ambitions than AppleScript automation, then this post is for you.

There are legitimate reasons why you may want to call out into something more powerful, like a Python script.

A quick aside: since you're still reading this post and are clearly ambitious: CurrentKey also lets you fetch its stats and tell it to go to specific Rooms programmatically. Here's a post about that.

Let's talk about why you'd make a shell command from your ck.scpt file. Why? Because doing so means CurrentKey's Room Change alerts can be a springboard for basically anything. Here, the shell command is to run a python script that writes the latest Room name to a file. Think of it as a "hello world" demo.

Here is the ck.scpt that will run a Terminal command to fire off a Python script. https://github.com/sdailey/CurrentKey_AppleScripts/blob/master/RoomChangeAlertScripts/execute_a_python_script/ck.scpt

Here is the proof-of-concept Python script itself, which will write the latest roomName to a file: https://github.com/sdailey/CurrentKey_AppleScripts/blob/master/RoomChangeAlertScripts/execute_a_python_script/yoyo.py

The comments in the files themselves tell you where they need to be placed. Once they're in the right directories on your Mac, and you enable Room change alerts in your Background Services panel, the python script will be called with the Room name each time you change Spaces.

In the example ck.scpt file, you can substitute that command (which runs the python script) for any other shell command you can think of, and it should run it! Enjoy the power.