Python: use pyenv to manage the version of Python

Table of Contents

Table of Contents

Environment

  • MacOS 11.2
  • Homebrew 3.1.5

Install pyenv

Use Homebrew to install pyenv.

brew update
brew install pyenv

Define environment variable

cp ~/.bash_profile ~/.zprofile

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zprofile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zprofile
echo 'eval "$(pyenv init -)"' >> ~/.zprofile

source ~/.zprofile

# check
echo $PATH

Install a specific version of python

show the list of installable versions

Use pyenv install --list to check the list.

pyenv install --list

Available versions:
  ...
  2.7.0
  3.7.0
  3.8.0
  3.9.0
  3.9.1
  3.9.2
  3.9.3
  3.9.4
  3.10.0a7
  3.10-dev
  anaconda-1.4.0
  ...

Install python3.9.4

If want to install python3.9.4, then use pyenv install <verison> to install the specific version of python.

pyenv install 3.9.4

Use pyenv versions to check if the specific version of python is installed or not.

pyenv versions
# results
system
* 3.9.4 (set by /Users/username/.pyenv/version)

Switch the global or local version

Use pyenv global <version> or pyenv local <version> to switch version of python.

pyenv global 3.9.4
# use `pyenv local 3.9.4` if want to change python's version for local directory. 

# check
python --version

Reference

Summary

  • Use Homebrew to install pyenv.
  • Use pyenv install --list to check the list.
  • Use pyenv versions to check if the specific version of python is installed or not.
  • Use pyenv global <version> or pyenv local <version> to switch version of python.