Skip to main content

Managing Python Installations With pyenv

Published

I’ve moved almost all of my development out of virtual machines in VMWare Fusion and onto my local computer and containers. Containers work great for building deployment but when I’m using PyCharm I want to have different versions of Python available and not have crap spewed all over the file system. The best way to do that on macOS is with a tool called pyenv.

To install pyenv, first install Homebrew:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
brew update
brew upgrade
brew install pyenv pyenv-virtualenv

To activate Homebrew, add this to ~/.zprofile:

# initialize homebrew (path is /usr/local/bin/brew on Intel Apples)
eval "$(/opt/homebrew/bin/brew shellenv)"

To activate pyenv, add this to ~/.zshrc:

# used by the PS1 environment variable
__pyenv_version() {
    local ret=$?;
    if [ -n "${PYENV_VIRTUAL_ENV}" ]; then
        echo -n "(${PYENV_VIRTUAL_ENV##*/}) "
    fi
    return $?
}

# then set up pyenv
export PYENV_ROOT="$HOME/.pyenv"
export PYENV_VIRTUALENV_DISABLE_PROMPT=1
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init --path)"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

# keep the prompt up to date
setopt PROMPT_SUBST
PS1="\$(__pyenv_version)${PS1}"

To see what Python versions are available:

pyenv install -l

To see what Python versions are installed:

pyenv versions

To activate a Python version (or virtualenv) for a certain directory:

echo "3.9.11" > .python-version

OR

pyenv local 3.9.11

To activate a Python version globally:

pyenv global 3.9.11

To create a virtual environment to be used in the current directory:

pyenv virtualenv 3.9.11 foobar

This creates a file called .python-version in your current directory. You should not add this file to source control.

To activate a specific virtual environment:

pyenv activate foobar

To deactivate the virtual environment:

pyenv deactivate

To remove a Python installation:

pyenv uninstall 3.9.11

You cannot uninstall a Python installation that has virtual environments.

To use your virtual environments in a tool like PyCharm, look for them here:

$PYENV_ROOT/versions/foobar/bin

In most cases $PYENV_ROOT will be ~/.pyenv.