I have been working on my automation lately and needed to add a python script to Keyboard Maestro I came across a small problem. I needed a couple of modules installed for the script to work, but I have my Macbook configured to only allow the installation of python modules if I am running inside a virtual environment. I could override my policy and install the modules locally, but I really prefer the cleanness that having virtual environments allows.

I started doing some research and came across this post that shows how to activate a python virtual environment from inside a script file. It turns out to be pretty straight forward. First, you create a new python virtual environment (I prefer virtualenvwrapper):

mkvirtualenv km

Then add the following to the beginning of your script file and then replace <PYTHON CODE> with your actual code.

#!/Users/mark.honomichl/.virtualenv/km/bin/python

activate_this = ""/Users/mark.honomichl/.virtualenvs/km/bin/activate_this.py"
with open(activate_this) as f:
        code = compile(f.read(), activate_this, 'exec')
        exec(code, dict(__file__=activate_this))

<PYTHON CODE>

I’ve created a repository for my all my Keyboard Maestro scripts, as well as a requirements.txt file to install the modules used by the scripts in case I ever need to recreate the virtual environment.