Install Python 3 on MacOS

The MacOS comes with an old version of Python 2. For new software development Python 3 is the recommended version. Replacing the original Python 2 with Python 3 can cause instability in the MacOS. There are multiple ways to install Python 3 and keep Python 2 pn the Mac. This is the most recommended process:

Use Pyenv

Pyenv is a Python version manager. It is recommended, because using it we can install and utilize multiple Python versions.

Install Pyenv

We will use Homebrew to install Pyenv

brew install pyenv

Install the latest stable version of Python with Pyenv

Check https://www.python.org/downloads/macos/ for the latest stable release.

pyenv install 3.9.6

Set the new Python version the default

pyenv global 3.9.6
# check if the change took effect
pyenv version

Configure your shell to use Pyenv for Python version management

Add these lines to your .bashrc, .zshrc or .bash_profile file

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

if command -v pyenv 1>/dev/null 2>&1; then
  eval "$(pyenv init -)"
fi

Check the default Python version

Open a new terminal window fo these configuration changes to take effect

python --version

Troubleshooting

During the installation I have encountered the following error messages

Error: The following directories are not writable by your user:
/usr/local/bin

You should change the ownership of these directories to your user.
sudo chown -R $(whoami) /usr/local/bin

To set you as the owner of the /usr/local/bin directory execute

sudo chown -R $(whoami) /usr/local/bin

Error:
homebrew-core is a shallow clone.
To brew update, first run:
git -C /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core fetch –unshallow

To update the shallow clone of the repository from GitHub execute

git -C /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core fetch --unshallow

Error: The following formula cannot be installed from bottle and must be
built from source.
python@2
Install the Command Line Tools:
xcode-select –install

To install the xcode command line developer tools execute

xcode-select --install

Leave a comment

Leave a Reply