Skip to content

Instantly share code, notes, and snippets.

@navigatingbots
Forked from ZhangChen199102/.direnvrc
Last active June 14, 2025 10:42
Show Gist options
  • Select an option

  • Save navigatingbots/37acd087a98700d90e3dc069cdec2346 to your computer and use it in GitHub Desktop.

Select an option

Save navigatingbots/37acd087a98700d90e3dc069cdec2346 to your computer and use it in GitHub Desktop.
Setup direnv + pyenv + pyenv-virtualenv
# use a certain pyenv version
use_python() {
if [ -n "$(which pyenv)" ]; then
local pyversion=$1
pyenv local ${pyversion}
fi
}
layout_virtualenv() {
local pyversion=$1
local pvenv=$2
if [ -n "$(which pyenv-virtualenv)" ]; then
pyenv virtualenv --force --quiet ${pyversion} ${pvenv}-${pyversion}
fi
pyenv local --unset
}
layout_activate() {
if [ -n "$(which pyenv)" ]; then
source $PYENV_ROOT/versions/$1/bin/activate
fi
}
# python version will be used for this project.
pyversion=3.6.4
# virtualenv name
pvenv=project1_env
# use a certain pyenv version
use python ${pyversion}
# Create the virtualenv if not yet done
layout virtualenv ${pyversion} ${pvenv}
# activate it
layout activate ${pvenv}-${pyversion}
# add environment variable here
export ENVIRONMENT_VARIABLE="first_environment_variable"

Install and setup

  1. Install pyenv and pyenv-virtualenv

     brew install pyenv
     brew install pyenv-virtualenv
    
  2. Install different versions of python

    pyenv install 3.6.4
    pyenv install 3.6.0
    
  3. Install direnv

    brew install direnv
    
  4. Update ~/.bash_profile

    echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
    echo 'eval "$(pyenv init -)"' >> ~/.bash_profile
    echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bash_profile
    echo 'eval "$(direnv hook bash)"' >> ~/.bash_profile
    
  5. Restart shell

  6. Add .direnvrc under ~/

In use

  1. Create a project directory.

    mkdir project_1
    
  2. Add .envrc under ./project_1

  3. Enter the project directory, run this command to trust current environment, you only need to run this at this first time and once .envrc is updated.

    cd projects_1/
    direnv allow
    

Now anytime you enter ./project_1/ or a directory under it, the virtualenv will automatically be activated, and environment variables will be setup.

  1. For IDE virtualenv setup, the virtualenv is under ~/.pyenv/versions/virtualenv_name/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment