How to Install and Use Python 3 on macOS
Python 3 was released quite a few years ago, so if you haven't made the switch yet from Python 2, it's probably time to start! This guide will show you how to install and use Python 3 on your Mac.
Python 3 was released quite a few years ago, so if you haven't made the switch yet from Python 2, it's probably time to start! This guide will show you how to install and use Python 3 on your Mac.
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.
At the top of your script you can include a shebang like so:
#!/usr/bin/env python3
and make sure the script is executable:
chmod +x path/to/script.py
Now when you run:
./path/to/script.py
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.
Another simple way is to just call python3
directly:
python3 path/to/script.py
This will ensure your script is run using Python 3 rather than the system python.
If it's been a while since you first installed Python, it might be time to check out the latest edition: Python 3. It has plenty of cool new features from data classes to typing enhancements.