Trigger python script, pass KM variables

I'd like to create a macro that copies text to the clipboard, activates a Python script that acts on the system clipboard, stores the results in KM variables, then does more KM actions on those variables. What I can't figure out is how to pass variables (and specifically the system clipboard) to a Python script and back.

1 Like

I’m no python expert but others are. Maybe this will help you:

1 Like

See Execute a Shell Script action for details on passing variables to and from script.

For specifics on python, you will have to know how Python reads environment variables, and/or uses AppleScript, and/or how to print results so that the output can be processed by the action and stored into a variable.


Plain text only, and only the system clipboard? Probably the easiest way is to use the pyperclip module in your Python script.

After a few hours of digging around the forum, I was about to execute the following python script file:

I did this using the Execute Shell Script action below:

However, the script gives a "Read-only file system" error in the log when it is run. Is this an issue related to the path? Or something else entirely?

2022-05-18 09:59:58 Execute a Shell Script failed with script error: Traceback (most recent call last):
  File "/Users/[user]/Downloads/", line 8, in test
    with open("TEST.txt", "x") as f:
OSError: [Errno 30] Read-only file system: 'TEST.txt'. Macro “Trying” cancelled (while executing Execute Shell Script).

$(which python) is probably getting you version 2.7.2, which doesn't have an "x" mode (IIRC). Try using "a" (append) if you want to add to a file, or "w" to overwrite the current contents.

Using "w" yields the same result...

Then it's your path to the file as well -- try an explicit open ("/Users/[user]/Desktop/TEST.txt", "w")

Once you've got it working you can worry about whether you actually need to use a relative/variable path rather than an absolute.

And please, please, please close the file when you've finished! f.close() at the end of your test function is enough.


For any future users with the same question, this is the script that ended up working for me:

#!/usr/bin/env python3

import os

def example():
	example_variable = str(os.environ["KMVAR_Variable_Name"])

	with open("/Users/USER/Downloads/TEST.txt", "x") as f:


# Execute the following from an "Execute Shell Script" action in Keyboard Maestro
# with input from text to pass multiple variables
# $(which python3) /Users/USER/Downloads/