Using brew for having multiple versions of Python is a common approach, but it can be troublesome when trying to install very specific versions. Problems with the linking are also frequent, but what alternative do we have?
Fortunately to solve these problems and waste no time setting up virtual environments we can use an awesome tool: pyenv
Installing pyenv + pyenv-virtualenv
For this tutorial I am assuming Home Brew is installed.
- Go to your terminal and install pyenv and the external libraries needed by Python:
brew update
brew install pyenv openssl readline sqlite3 xz zlib
- 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
- Install the pyenv-virtualenv plugin so you can create virtual environments running any version of Python. Just paste 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
- Reset your terminal to apply the changes with
exec "$SHELL"
or just close it 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.
To create a new virtual environment:
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
To remove an existing virtualenv use any of the following options:
pyenv uninstall MY_VIRTUALENV_NAME
pyenv virtualenv-delete MY_VIRTUALENV_NAME