How to Work with Python on macOS / Mac OS X

The macOS / Mac OS X operating system comes pre-installed with the libraries needed to run Python programs. You can interact with Python programs via the Terminal application (Applications -> Utilities -> Terminal). To determine the version of Python installed, type the following in the Terminal window and then hit enter/return:

python

This will display the version of Python pre-installed on the operating system. For example, this may display 2.6.1

Python programs can be created using any text editor such as EditRocket. Python programs and scripts typically end with the .py extension. EditRocket will automatically recognize files with the .py extension as Python programs, and will color the syntax accordingly.

To create a Python program, simply create a new file, such as hello.py. In the file, place the following:

import sys
sys.stdout.write("Hello, world!\n")

The above script can be executed using the EditRocket Tools -> Python -> Execute Program option, or you can execute it from the Terminal window. To execute the script in the Terminal, use the cd command to cd to the directory where the hello.py file was saved, such as

cd /Users/user/Desktop

Then type the following:

python hello.py

Hello World! should then be printed to the screen.

For more information about runing Python programs via the local Mac OS X Apache web server, see the following:

Running Python with the Apache Web Server on Mac