Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Setup direnv + pyenv + pyenv-virtualenv
# use a certain pyenv version
use_python() {
if [ -n "$(which pyenv)" ]; then
local pyversion=$1
pyenv local ${pyversion}
layout_virtualenv() {
local pyversion=$1
local pvenv=$2
if [ -n "$(which pyenv-virtualenv)" ]; then
pyenv virtualenv --force --quiet ${pyversion} ${pvenv}-${pyversion}
pyenv local --unset
layout_activate() {
if [ -n "$(which pyenv)" ]; then
source $PYENV_ROOT/versions/$1/bin/activate

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 ~/.zshrc

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

  6. Add .direnvrc under ~/

In use

  1. Create a project directory.

    mkdir project_1
  2. Create virtual environment:

    pyenv virtualenv 3.6.7 venv-name
  3. Create .python-version under ./project_1 with the virtual environment name created in step 2.

  4. Create .envrc under ./project_1 with environment variables declaration like: export ENV_VARIBALE_NAME=bla

  5. 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