direnv with python
What is direnv
direnv
is a tool that allows you to change your environment based on the configuration in that folder.
e.g. You can set different environment variables for different folders.
The reason I revisited direnv
is because for python project, we need to switch to different virtual environment each time we change a project.
Wouldn’t it be nice if correct virtual environment was activated when you change to that directory
and unload everything to the way it was, when you switch away
How to use it with python project ?
Option 1 1
Create following in ~/.config/direnv/direnvrc
activate_virtualenv() {
export VIRTUAL_ENV=$1
PATH_add "$VIRTUAL_ENV/bin"
}
Then, in the .envrc
of that folder, add activate_virtualenv path/to/virtualenv
Option 2 2
Other option is to add just single line layout python3
to your .envrc
This automatically creates and activates .direnv/python-$python-version
If you want to control the name and location of your virtual environment then
your .envrc
should have the following
export VIRTUAL_ENV="my_venv"
layout python3
In both scenario, you’ll need to type direnv allow
on the terminal the first
time. Otherwise, contents of .envrc
will not be executed.
Go through the README to learn more about this amazing tool.