Installing multiple Python versions in Mac (OS X)

In this tutorial I am assuming Home Brew is installed.

Installing pyenv + pyenv-virtualenv

  1. Go to your terminal and install pyenv and the external libraries needed by Python:
    brew update
    brew install pyenv openssl readline sqlite3 xz zlib

  2. Add “pyenv init” to your shell to enable shims and autocompletion running the following command:
    echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.bash_profile

  3. Install the pyenv-virtualenv plugin so you can create virtual environments for each version of Python. Run the following two lines in your terminal:
    git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv
    echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bash_profile
    
  4. Reset your terminal to apply the changes exec "$SHELL" or just close your terminal and open a new one.

Installing different Python versions

First list all the available versions:
pyenv install --list
For instance we will install the Python version 3.7.2:
pyenv install 3.7.2

With pyenv versions you can see all the Python versions installed in your computer:

root@Host ~$ pyenv versions
* 3.7.2

Creating a virtual environment

In the previous step we have downloaded the Python 3.7.2 interpreter, we can now use it to create an isolated virtual environment. This is very useful for software development, keeping each project completely isolated from the others.
pyenv virtualenv 3.7.2 MY_VIRTUALENV_NAME

To list all your virtual environments:
pyenv virtualenvs

To activate a virtual environment:
pyenv activate MY_VIRTUALENV_NAME

To deactivate the currently active virtual environment:
pyenv deactivate

Leave a Reply

Your email address will not be published. Required fields are marked *