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
Open Terminal.app (~/Applications/Utilities) and type python --version
If you execute this command in macOS 10.13.x for example, the returned output will read:
Python 2.7.10
If you execute which python
via the command line, it will return the location of the program file, in this case:
/usr/bin/python
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:
Python 3.6.4
Now run which python3
to determine the path where Homebrew installed the progam file:
/usr/local/bin/python3
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.
python test.py
- to run a script with Python 3, eg.
python3 test.py
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:
- via
source ~/folderA/bin/activate
, if you wish to use the Python 2 environment - via
source ~/folderB/bin/activate
, if you wish to use the Python 3 environment
To exit an environment use deactivate
Once you've activated a virtual environment, you can just use python
to execute your scripts.
Thanks for this! I keep forgetting how to do this, googling, and coming back to this page. This is the third or fourth time I've come back, so I figured I owed you a thank you.