How to Install Pyenv on MacOS

How to Install Pyenv on MacOS

There are a few ways on MacOS to install Python. You can install it via Brew, or by using Pyenv. After needing to switch between different versions of Python often I’ve decided to move to Pyenv. Prior to these steps I removed all versions of Python installed directly with Brew.

Update Brew and install prerequisites

We will need to update brew.

1
brew update

In some cases when installing Python >=3.12.1 we will need ncurses. If it’s missing you can install using:

1
brew install ncurses

Install Pyenv using brew

The recommended way to install pyenv on MacOS is brew.

1
brew install pyenv

Brew doctor fix

If you want to avoid brew doctor warning about “config” scripts existing outside the system or Homebrew directories please include the following in your shell.

1
alias brew='env PATH="${PATH//$(pyenv root)\/shims:/}" brew'

Configure your Zsh profile.

1
2
3
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
echo 'eval "$(pyenv init -)"' >> ~/.zshrc

If you wish to use Pyenv in non-interactive shells, add the following:

1
2
3
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zprofile
echo '[[ -d $PYENV_ROOT/bin ]] && export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/. zprofile
echo 'eval "$(pyenv init -)"' >> ~/.zprofile

Restart shell

1
exec "$SHELL"

Install python 3.12

I am going to show how to install python 3.12 but you can select any version of your choice.

1
pyenv install 3.12

Switch between your python versions

1
2
3
4
5
pyenv shell <version> – modifies python for the current shell session

pyenv local <version> – modifies the python used in the current directory (or subdirectories)

pyenv global <version> – modifies the python used for your user account
-------------本文结束感谢您的阅读-------------