Python environments in macOS
The latest version of macOS 10.13.3 has Python 2.7.10 installed by default, yet Python has been available on macOS and previously OS X for quite a while now.
Consult the Apple's Open Source Reference Library, and browse through the various releases of the OS to find out which Python version was included). But what if you have a project which requires Python 3 ?
The following instructions will guide you through the process of:
- installing Python 3 using Homebrew
- running multiple Python verions as sandboxed environments
Installed version of Python
Open Terminal.app (~/Applications/Utilities) and type
If you execute this command in macOS 10.13.x for example, the returned output will read:
If you execute
which python via the command line, it will return the location of the program file, in this case:
Install Python 3 with Homebrew
Great so we have access to Python 2.x, now lets add Python 3.x
Assuming you have Homebrew installed, in Terminal.app execute the following command to install Python 3 :
brew install python3. After installation, run the
python3 --version command to verify the exact version:
which python3 to determine the path where Homebrew installed the progam file:
At this stage we have two different version of Python available, yet both version are invoked differently :
- to run a script with Python 2, eg.
- to run a script with Python 3, eg.
Isolated Python environments using virtualenv
If you have different projects developed in either Python 2 or 3 and each requiring specific libraries, you might consider using sandboxed Python environments. This can be achieved with virtualenv
As an example we have two directories: folderA and folderB.
- ~/folderA will be used for the Python 2 virtual environment
- ~/folderB will be used for the Python 3 virtual environment
Open Terminal.app and type
pip3 install virtualenv, which should result in:
Successfully installed virtualenv-15.1.0
Create the different environments:
- Python 2 based virtual environment via
virtualenv -p python ~/folderA
- Python 3 based virtual environment via
virtualenv -p python3 ~/folderB
Activate the Python environment:
source ~/folderA/bin/activate, if you wish to use the Python 2 environment
source ~/folderB/bin/activate, if you wish to use the Python 3 environment
To exit an environment use
Once you've activated a virtual environment, you can just use
python to execute your scripts.