Python Reading KM Variable in PyCharm Encounters Error

Hi,
When I try to read a KM variable into Python, I'm encountering an error.

A simple code:

#!/usr/bin/python3
import os
v = os.environ['KMVAR_Var']
print(v)

Error:

Traceback (most recent call last):
File "/Users/UserName/PycharmProjects/practice/tempUse.py", line 3, in
v = os.environ['KMVAR_Var']
File "/usr/local/Cellar/python@3.9/3.9.5/Frameworks/Python.framework/Versions/3.9/lib/python3.9/os.py", line 679, in getitem
raise KeyError(key) from None
KeyError: 'KMVAR_Var'

I searched elsewhere and have not been able to find a solution.
Can anyone help?

If I execute the python file in KM. It runs successfully. So the problem is probably with PyCharm.

Thanks!

While you are correctly getting the KM variable from the environment, the environment has to be the KM one - not any other shell which is why your script works when called from within KM. The variable simply does not exist outside KM.

1 Like

Thanks, @tiffle. That's very helpful!
Does this mean I will never be able to read KM variables if the python is not executed by Keyboard Maestro? Or is there a way to do that? KM is not a good place to debug my code. I'd like to write and test the code in PyCharm and then hand it over to KM.

As @ccstone put it:

"You cannot access Keyboard Maestro shell variables outside of its Execute a Shell Script actions, because the variables are exported to the action at runtime."

in this thread:

1 Like

What I've done when debugging AppleScript in Script Debugger is to replace those bits of code that access KM variables with simple variable assignments, so the code gets the variable values from the assignments rather than trying to access the KM environment. Then, when debugging is over (if it ever is!) I comment out those assignments and reinstate the code that accesses KM. You could do the same in Python.

It's a lot easier to do than describe but as a workaround it's OK.

1 Like

Thanks! That's very helpful! I've also learned from there that running AppleScript in Python can get the variables.

Thanks! Now I've understood the issue. I probably will do the same.

1 Like

I missed that - it's a pretty clever way to do it!

1 Like