SOLVED - Call a Keyboard Maestro variable in python running in 'Execute Shell Script'?

I have a python script that works with a file name but not when I replace the file name with the Keyboard Maestro variable $KMVAR_fName. When I use $KMVAR_fName it reports in the Engine.log

FileNotFoundError: [Errno 2] No such file or directory: '$KMVAR_fName'. Macro “Trying” cancelled (while executing Execute Shell Script).

I've cut and pasted the file name that works into Keyboard Maestro variable fName and it still reports "no such file".

Here is the python code.

#!/usr/bin/env python3
# encoding: utf-8

def check(token):
    with open("$KMVAR_fName") as f:
        datafile = f.readlines()
    for line in datafile:
        if token in line:
            return line.partition("Subatomic: ")[2]
    return False  # Because you finished the search without finding
    # Use    
output = (f'\t\t- {check("Subatomic: ")}')  

This is the file name I'm using for testing and is 'fName'.
/Users/will/Dropbox/zettelkasten/Creative Pressure

Here is how I'm using this in Keyboard Maestro. Down near the bottom.

Copy Links.kmmacros (7.3 KB)

I am an expert in neither Python nor KM but are you sure that

with open("$KMVAR_fName") as f:

Is supposed to have $KMVAR_fName in quotation marks. Rather than just

with open($KMVAR_fName) as f:

1 Like

Since you reference a python file which is already on disc, then KM does not intepret the variables inside this file.
You could have an action before writing the python file to disc and then execute it. When writing the text to disc KM will replace the variable with the filename.

I do something similar automating some things with Adobe InDesign.

1 Like

Python accesses environment variables through the environ dictionary in the os library. So your script needs to include

import os

to import the library. Most people put their import statements up near the top of the script. Then you access the value of fName this way:

with open(os.environ["KMVAR_fName"]) as f:

Bingo! It now works. I can use Keyboard Maestro variables in python when I run those scripts via Keyboard Maestro.

Thanks for the clear explanation of where python accesses environment variables. This seems like basic stuff I should have known. Again thanks.