UPDATED: June 11, 2019
John asked me if I had written a blog post on getting my Mac setup with
pyenv. I hadn’t… So here it goes!
MacOS comes with Python 2.7 out-of-the-box. It’s great for first-timers and basic development, but as soon as you start working on more than one project you quickly realize that your projects may (will) have conflicting dependencies. One of those conflicting dependencies may be Python itself. How do you develop one project in Python 2.7 and another in Python 3.6? Enter
From the docs:
pyenv lets you easily switch between multiple versions of Python. It’s simple, unobtrusive, and follows the UNIX tradition of single-purpose tools that do one thing well.
Follow these steps to install
pyenv on macOS. We’ll be installing
pyenv via Homebrew so make sure you have it installed.
# Install Homebrew if it isn't already available
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" # Install pyenv
brew install pyenv # Add pyenv initializer to shell startup script
echo 'eval "$(pyenv init -)"' >> ~/.bash_profile # Reload your profile
pyenv is installed and functioning. Now we can install multiple versions of Python and switch between them seamlessly.
pyenv install <python-version>
You can view a full list of available versions with
pyenv install --list. Go ahead and install Python 3.7.2:
pyenv install 3.7.2
On some versions of MacOS you may encounter issues related to
zlib not being found.
Follow these instructions to install: https://github.com/pyenv/pyenv/wiki/common-build-problems#build-failed-error-the-python-zlib-extension-was-not-compiled-missing-the-zlib
View Installed Versions
Now that we’ve installed Python 3.7.2 let’s take a look at all the installed versions available on our system:
You should see
Set Global Python
pyenv global 3.7.2
Now whenever you call
python you’ll be using Python 3.7.2. Check it with
Set Local Python
To set a Python version for a specific project,
cd into your project and then run:
pyenv local <python-version>
That will create a
.python-version file in the current directory which
pyenv will see and use to set the appropriate version.
pyenv is a great tool for managing projects that depend on different versions of Python, but it doesn’t help us if we have two projects that use the same version of Python with different versions of
pip packages. Check out Part 2: Python Development on macOS with pyenv-virtualenv.