Kinsa | Pixels + Logic Blog

Installing Multiple Versions of Python Alongside Each Other on Apple Mac OS X with PyEnv

Install pyenv using Homebrew. You may need to install Homebrew first if you haven't used it before. If it has been a while, run brew update first to update the formulae and Homebrew itself:

$ brew install pyenv

Update the path to use pyenv shims: edit ~/.zshrc (if you're running Mac OS Catalina which uses ZSH as the default shell) to include:

PATH=$(pyenv root)/shims:$PATH

You might have to create ~/.zshrc if you haven't edited it before: $ vim ~/.zshrc will create it and open it for editing.

After saving, start a new Terminal window.

Find the latest Python version from available installations:

$ pyenv install --list

Install the latest version of Python (3.8.2 at the time of this writing):

$ pyenv install 3.8.2

Make that the global default version:

$ pyenv global 3.8.2

Install another version of Python, for example Python 2.7.17:

$ pyenv install 2.7.17

After setting the global, start a new Terminal window.

Verify the global version:

$ which python
/Users/kinsa/.pyenv/shims/python
$ python -V
Python 3.8.2

If a project needs to use a specific version, from the project directory create a .python-version file by specifying local before the version number:

$ pyenv local 2.7.17

You may need to first get a list of installed versions by running:

$ pyenv versions

Once specified, you can verify that it it set:

$ python -V
2.7.17
$ cat .python-version
2.7.17

Setup a virtual environment using that version of Python and activate it. If the version of Python is 3.x, you can use Python 3's built in venv package. From the project directory:

$ python -m venv .venv
$ source .venv/bin/activate
(.venv) $ which python
...venv/bin/python

If the version of Python is 2.x, you will need to use the 3rd party virtualenv package. From the project directory:

$ pip install virtualenv
$ virtualenv .venv
$ source .venv/bin/activate
(.venv) $ which python
...venv/bin/python

Add .venv to your .gitignore:

$ echo ".venv" >> .gitignore

Use pip to install project-specific Python packages:

$ pip install spam

Revisions

May 27, 2020
Noted the need to run `brew update` if it has been a while since Homebrew was installed or last updated. Updated the language throughout for clarity.

Feedback?

Email us at hello@kinsa.us.