Python is a versatile and widely used programming language that comes pre-installed on macOS. In this tutorial, we will learn how to run Python directly in your Mac terminal.
Step 1: Open Terminal
To start, open the Terminal app on your Mac. You can find it in the Applications/Utilities
folder or by searching for it using Spotlight (Cmd + Spacebar).
Step 2: Check Python Version
macOS comes with Python 2.7 pre-installed, but it’s recommended to use Python 3 since Python 2 is no longer supported. To check the Python version installed on your system, enter the following command in Terminal:
python --version
If you see Python 3.x.x, then you’re good to go. However, if you see Python 2.7.x or don’t have Python 3 installed, follow the instructions in the next section to install Python 3.
Step 3: Install Python 3 (if needed)
To install Python 3, we recommend using Homebrew, which is a package manager for macOS. First, install Homebrew by running the following command in Terminal:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Once Homebrew is installed, you can install Python 3 by entering the following command:
brew install python
After the installation is complete, you can check your Python version again using the python3 --version
command.
Step 4: Run Python in Terminal
To run Python directly in Terminal, just type python3
and hit Enter. This will start the Python interpreter, and you’ll see the following output:
Python 3.x.x (default, date and time, [Clang/GCC] on darwin)
Type "help", "copyright", "credits" or "license" for more information.
>>>
You can now enter Python commands and see their output directly in Terminal. For example, you can perform an addition by typing 2 + 3
and pressing Enter:
>>> 2 + 3
5
To exit the Python interpreter, press Ctrl + Z (or type exit()
and press Enter).
Step 5: Run Python Scripts
To run a Python script in Terminal, navigate to the directory containing the script using the cd
command. For example, if your script is located in the Documents/PythonScripts
folder, you’d enter:
cd ~/Documents/PythonScripts
Once you’re in the correct directory, run the script using the python3
command followed by the script’s file name. If your script is named my_script.py
, the command would be:
python3 my_script.py
Your script will now run, and you’ll see its output in Terminal.
Conclusion
Running Python on Mac Terminal is simple and straightforward. With just a few commands, you can start using Python directly in your terminal or execute Python scripts. Happy coding!