Skip to content

Instantly share code, notes, and snippets.

@ZhangChen199102
Last active April 1, 2024 03:48
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ZhangChen199102/da3133fc05e3b03afab405fdc3152fb3 to your computer and use it in GitHub Desktop.
Save ZhangChen199102/da3133fc05e3b03afab405fdc3152fb3 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
}

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.

    venv-name
    
  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 created virtualenv is under directory ~/.pyenv/versions/virtualenv_name/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment