Using pyenv to Manage Python Versions
Table of Contents
During development, you may require different Python versions for various projects. For example, you might need Python 3.6 for one project and Python 3.10 for another. Instead of installing different Python versions on your system, you can use pyenv to manage multiple Python versions.
#
Install pyenv
You can see the instructions from the official website. Take MacOS as an example, you can install pyenv with Homebrew:
$ brew update
$ brew install pyenv
After installation, you need to add the following lines to your shell profile file (e.g. ~/.zshrc
):
$ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.zshrc
$ echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.zshrc
$ echo 'eval "$(pyenv init -)"' >> ~/.zshrc
Restart your shell, and you can use pyenv
command now.
$ exec "$SHELL"
$ pyenv version
#
Install python version
You can use pyenv install -l
to list all available Python versions. For example, you can install python 3.10 with the following command:
$ pyenv install 3.10
You can use pyenv versions
(do not forget the s
) to list all installed python version.
#
Switch python version
To specify a Python version for a project, use the pyenv local command. For instance, to enable Python 3.10 for the current directory, use the following command:
$ pyenv local 3.10
In the current directory, you’ll find a file named .python-version containing the specified Python version. When you use the which python command, you’ll observe that ‘python’ is using the version you’ve specified.
$ which python
With the setting above, you can create a virtual environment and use this environment to install project dependencies with the following command:
$ python -m venv .venv
$ . .venv/bin/activate
$ which python # You will see it is using the python in the virtual environment.
# pip install ...
Similarly, if a project requires a different Python version, install it using pyenv and create a virtual environment for the project as needed.
#
Learn More
- Managing Multiple Python Versions With pyenv. This post offers comprehensive information on using
pyenv
in various scenarios