Read our guide to learn how to install Homebrew on your Mac if it's not already installed.
Once Homebrew is installed, you can install Python 3 easily by typing:
brew install python
Once the installation finishes, you can confirm by typing:
[~]$ python3 --version Python 3.6.5
You may notice
python command still uses the system python, Python 2.7:
[~]$ python --version Python 2.7.10
We'll address this in a later step!
I recommend virtualenv and virtualenvwrapper for working with virtual environments in Python. Check out our guide to learn how to work with virtual environments using virtualenv and virtualenvwrapper.
Using these tools, you can run Python 3 in a virtual environment by running the following:
mkvirtualenv -p /usr/local/bin/python3.6 myenv
This will create the virtual environment and put you in the newly created environment. Run the following to confirm your Python version:
(myenv) [~]$ python --version Python 3.6.5
Notice the environment name is in parenthesis above the prompt. This is just to remind you which environment you're in.
If you're not operating in a Python 3 virtual environment, and you want to run scripts using Python 3 there are two easy ways.
Use a shebang
At the top of your script you can include a shebang like so:
and make sure the script is executable:
chmod +x path/to/script.py
Now when you run:
it will be run using Python 3. More specifically, the program loader sees the shebang line and knows to call the
python3 program and pass in
path/to/script.py as the first argument.
Using python3 directly
Another simple way is to just call
This will ensure your script is run using Python 3 rather than the system python.