DEV Community

Jay
Jay

Posted on • Originally published at jay.gooby.org on

asdf, python and automatically enabling virtual envs

I've switched wholly to asdf for all my projects now, both work and personal, thanks to @emma who first put me on to it. In the day job, it's used for managing ruby and node versions with the asdf-ruby and asdf-nodejs plugins.

I've started to use the asdf-python plugin here on this blog, as I have a small python script I use to extract my music posts from Slack to archive to my Music I've liked page.

When I first switched over, everything stopped working, because I'd forgotten to first enable the python virtual env by calling source env/bin/activate. I've since forgotten to do this a couple of times, so it's time to automate!

autoenv will run commands in a .env file when you cd into a directory, and will also run any in .env.leave when you cd out, so it's perfect for setting and unsetting your python env.

I installed autoenv, and created the .env and .env.leave files:

echo -e "AUTOENV_ENABLE_LEAVE=1\nsource \"$AUTOENV_CUR_DIR/env/bin/activate\"" > .env
echo deactivate > .env.leave
Enter fullscreen mode Exit fullscreen mode

Then when you next cd into your project folder, you'll be prompted:

autoenv:
autoenv: WARNING:
autoenv: This is the first time you are about to source /Users/jay/Library/CloudStorage/Dropbox/Work/gooby.org/2021/2021.gooby.org/.env:
autoenv:
autoenv:   --- (begin contents) ---------------------------------------
autoenv:     AUTOENV_ENABLE_LEAVE=1$
autoenv:     source "$AUTOENV_CUR_DIR/env/bin/activate"$
autoenv:
autoenv:   --- (end contents) -----------------------------------------
autoenv:
autoenv: Are you sure you want to allow this? (y/N)
Enter fullscreen mode Exit fullscreen mode

to check you really want to run that .env in the future. Ditto the first time you cd out of the project1:

autoenv:
autoenv: WARNING:
autoenv: This is the first time you are about to source /Users/jay/Work/gooby.org/2021/2021.gooby.org/.env.leave:
autoenv:
autoenv:   --- (begin contents) ---------------------------------------
autoenv:     deactivate$
autoenv:
autoenv:   --- (end contents) -----------------------------------------
autoenv:
autoenv: Are you sure you want to allow this? (y/N)
Enter fullscreen mode Exit fullscreen mode

From then on, you won't see the prompts again. You can hide them completely if you add AUTOENV_ASSUME_YES=1 to the top of both .env and .env.leave.


  1. Because we're passing the full path to activate in the .env file using source "$AUTOENV_CUR_DIR/env/bin/activate", if we cd within the project folder structure, we'll still keep our activated environment, because autoenv looks for a parent .env file. If we just had source env/bin/activate then we'd lose the environment activation, because the path to env/bin/activate is relative and would no longer be correct. 

Top comments (0)