Python variable value to KM Variable value

This took me a little bit of effort to figure out so thought I would share.

When executing a Python script within a KM macro, it is well documented how to use a KM Variable's value in a Python script see here.

Unfortunately, it is not supported natively to send information back to KM using Python to set a KM Variable's value from within the Python script. It can be done using AppleScript from within the Python script but I have not seen any code examples so I thought I would include one:

import subprocess

# insert your python script here

python_output = "Data that you want to set a KM variable to."

applescript_command = f"""osascript -e 'tell application "Keyboard Maestro Engine" to setvariable "km_variable_name" to "{python_output}"'"""

subprocess.run(applescript_command, shell=True)

Hope that helps someone!

7 Likes

While I am just barely learning shell scripts (and haven't delved into Python yet), I'm bookmarking this for future use.

Thanks for sharing!

-Chris

1 Like

Just what I was looking for today! Thanks for leaving the tip :+1:

Awesome! Glad it was useful to you!