5. Using Python on a Mac¶
Python on a Mac running macOS is in principle very similar to Python on any other Unix platform, but there are a number of additional features such as the IDE and the Package Manager that are worth pointing out.
5.1. Getting and Installing MacPython¶
macOS used to come with Python 2.7 pre-installed between versions 10.8 and 12.3. You are invited to install the most recent version of Python 3 from the Python website (https://www.python.org). A current “universal binary” build of Python, which runs natively on the Mac’s new Intel and legacy PPC CPU’s, is available there.
What you get after installing is a number of things:
A Python 3.12 folder in your Applications folder. In here you find IDLE, the development environment that is a standard part of official Python distributions; and PythonLauncher, which handles double-clicking Python scripts from the Finder.
A framework /Library/Frameworks/Python.framework , which includes the Python executable and libraries. The installer adds this location to your shell path. To uninstall MacPython, you can simply remove these three things. A symlink to the Python executable is placed in /usr/local/bin/.
The Apple-provided build of Python is installed in /System/Library/Frameworks/Python.framework and /usr/bin/python , respectively. You should never modify or delete these, as they are Apple-controlled and are used by Apple- or third-party software. Remember that if you choose to install a newer Python version from python.org, you will have two different but functional Python installations on your computer, so it will be important that your paths and usages are consistent with what you want to do.
IDLE includes a help menu that allows you to access Python documentation. If you are completely new to Python you should start reading the tutorial introduction in that document.
If you are familiar with Python on other Unix platforms you should read the section on running Python scripts from the Unix shell.
5.1.1. How to run a Python script¶
Your best way to get started with Python on macOS is through the IDLE integrated development environment, see section The IDE and use the Help menu when the IDE is running.
If you want to run Python scripts from the Terminal window command line or from the Finder you first need an editor to create your script. macOS comes with a number of standard Unix command line editors, vim and emacs among them. If you want a more Mac-like editor, BBEdit or TextWrangler from Bare Bones Software (see http://www.barebones.com/products/bbedit/index.html) are good choices, as is TextMate (see https://macromates.com/). Other editors include Gvim (https://macvim-dev.github.io/macvim/) and Aquamacs (http://aquamacs.org/).
To run your script from the Terminal window you must make sure that /usr/local/bin is in your shell search path.
To run your script from the Finder you have two options:
Drag it to PythonLauncher
Select PythonLauncher as the default application to open your script (or any .py script) through the finder Info window and double-click it. PythonLauncher has various preferences to control how your script is launched. Option-dragging allows you to change these for one invocation, or use its Preferences menu to change things globally.
5.1.2. Running scripts with a GUI¶
With older versions of Python, there is one macOS quirk that you need to be aware of: programs that talk to the Aqua window manager (in other words, anything that has a GUI) need to be run in a special way. Use pythonw instead of python to start such scripts.
With Python 3.9, you can use either python or pythonw.
5.1.3. Configuration¶
Python on macOS honors all standard Unix environment variables such as PYTHONPATH , but setting these variables for programs started from the Finder is non-standard as the Finder does not read your .profile or .cshrc at startup. You need to create a file
/.MacOSX/environment.plist . See Apple’s Technical Document QA1067 for details.
For more information on installation Python packages in MacPython, see section Installing Additional Python Packages .
5.2. The IDE¶
MacPython ships with the standard IDLE development environment. A good introduction to using IDLE can be found at http://www.hashcollision.org/hkn/python/idle_intro/index.html.
5.3. Installing Additional Python Packages¶
There are several methods to install additional Python packages:
Packages can be installed via the standard Python distutils mode ( python setup.py install ).
Many packages can also be installed via the setuptools extension or pip wrapper, see https://pip.pypa.io/.
5.4. GUI Programming on the Mac¶
There are several options for building GUI applications on the Mac with Python.
PyObjC is a Python binding to Apple’s Objective-C/Cocoa framework, which is the foundation of most modern Mac development. Information on PyObjC is available from https://pypi.org/project/pyobjc/.
The standard Python GUI toolkit is tkinter , based on the cross-platform Tk toolkit (https://www.tcl.tk). An Aqua-native version of Tk is bundled with OS X by Apple, and the latest version can be downloaded and installed from https://www.activestate.com; it can also be built from source.
wxPython is another popular cross-platform GUI toolkit that runs natively on macOS. Packages and documentation are available from https://www.wxpython.org.
PyQt is another popular cross-platform GUI toolkit that runs natively on macOS. More information can be found at https://riverbankcomputing.com/software/pyqt/intro.
5.5. Distributing Python Applications on the Mac¶
The standard tool for deploying standalone Python applications on the Mac is py2app. More information on installing and using py2app can be found at https://pypi.org/project/py2app/.
5.6. Other Resources¶
The MacPython mailing list is an excellent support resource for Python users and developers on the Mac:
Как открыть питон на макбуке
Для создания программ на Python нам потребуется интерпретатор. Для его установки перейдем на страницу https://www.python.org/downloads/ и найдем ссылку на загрузку последней версии языка:

Если текущая ОС — Mac OS, то по адресу https://www.python.org/downloads/ будет предложено загрузить графический установщик для MacOS. Загрузим, запустим его и выполним пошаговую установку:

Для обращения к интерпретатору Python на MacOS применяется команда python3 . Напримерб после установки интерпретатора проверим его версию командой

Первая программа
Сначала определим где-нибудь на жестком диске для скриптов папку python . А в этой папке создадим новый текстовый файл, который назовем hello.py . По умолчанию файлы с кодом на языке Python, как правило, имеют расширение py .
Откроем этот файл в любом текстовом редакторе и добавим в него следующий код:

Скрипт состоит из двух строк. Первая строка с помощью функции input() ожидает ввода пользователем своего имени. Введенное имя затем попадает в переменную name .
Вторая строка с помощью функции print() выводит приветствие вместе с введенным именем.
Теперь запустим командную строку/терминал и с помощью команды cd перейдем к папке, где находится файл с исходным кодом hello.py (например, в моем случае это папка «/Users/eugene/Documents/python»).
Далее для выполнения скрипта hello.py передадим его интерпретатору python:
В итоге программа выведет приглашение к вводу имени, а затем приветствие.
Установка и настройка Pуthon, Django и virtualenv на Mac OS
Я начал изучать возможности Django. Но раньше я работал только с DLE CMS и WordPress. Поэтому решил почитать инструкции по установке и настройке Джанго, с учетом того, что у меня Mac OS.
Стоит немного остановиться на том, что такое Django. Это достаточно мощный и уважаемый среди разработчиков фреймворк для создания сайтов, написанный на Python. Django считается очен быстрым и безопасным фреймворком, а благодаря своей модульности он очень гибкий и хорошо масштабируется.
Есть очень много разных туториалов по установке, настройке и запуску Django. Но часть из них или достаточно объемные, или упускают какие-то важные вещи. В этой статье я постараюсь описать основные шаги, необходимые для запуска проекта на Python-Django под Mac OS.
Основные шаги:
- Установка Homebrew.
- Установка Python 3.
- Установка virtualenv.
- Создание изолированного окружения для проекта.
- Запуск изолированного окружения.
- Установка Django.
- Создание проекта.
- Запуск проекта!
Установка Homebrew
Homebrew — бесплатная открытая система управления программными проектами, которая упрощает установку программного обеспечения на операционную систему Mac OS. Homebrew использует Github для расширения поддержки пакетов, за счет вклада пользователей.
Если у вас не установлен Hombrew, необходимо запустить в терминале команду:
Установка Python3
Изначально Mac OS имеет предустановленный python версии 2. Поэтому, послу установки 3 версии питона, для доступа именно к python3 необходимо запускать его из терминала с командой python3.
Чтобы проверить версию python, надо запустить в терминале команду
Вы должны получить сообщение с версией установленного python.
Установка virtualenv
virtualenv — инструмент для создания изолированного виртуального окружения Python. Благодаря этому инструменту можно создать несколько разных проектов python, с разным набором библиотек на одном устройстве. Например, если вы захотите использовать разные версии одного и того же модуля в разных проектах.
После установки virtualenv мы установим все другие пакеты, в том числе и django в изолированные окружения.
Создание изолированного окружения для проекта
Создаем папку, в которой будет храниться проект. Пример команды в терминале.
И переходим в нее:
Создаем виртуальное окружение для проекта:
Где “ptest” — это название изолированного окружения, на ваше усмотрение.
Запуск изолированного окружения
После создания окружения, необходимо его активировать, чтобы установить все необходимые модули. Для этого запускаем в терминале команду:
Чтобы определить, в каком окружении вы находитесь, посмотрите на префикс в терминале, в круглых скобках будет указано название.
Так как изолированное окружение создавалось при помощи python3, в этом окружении можно запускать команды сразу через python, а не python3, так же как и pip, вместо pip3.
Чтобы завершить работу изолированного окружения, достаточно написать команду
Установка Django
Снова запустим изолированное окружение и через pip установим django.
Где “2.2” — необходимая версия джанго.
Создание проекта
Все готово для создания проекта. Достаточно написать в терминале (с запущенной виртуальной средой):
Поздравляю, вы создали свой первый проект на Django. Структура папок будет такой:
- project_test —домашняя папка проекта
- project1 — папка проекта django
- project1 — корневая папка
- ptest — виртуальная среда проекта
Запуск проекта
В Django встроен простой виртуальный веб-сервер. Не надо устанавливать никаких других программ на локальной машине. Чтобы его проверить, запустите в терминале команду:
Tutorial: Installing Python on Mac

Python is one of the most powerful programming languages, mostly used in data science, machine learning, and big data analytics. So, installing Python is essential for all programmers. As a novice programmer, you may be wondering how to install or update Python on your Mac properly. Here, we will walk through the different ways of installing and updating Python on macOS.
Then, to write and run our Python code in an integrated development environment (IDE), we will learn how to install and configure Visual Studio Code on Mac. There are different methods for installing and updating Python on Mac, but let’s stick to the third principle of the Zen of Python that says: “Simple is better than complex.” Accordingly, we will try simple methods rather than complex ones. Before we jump into learning how to install or update Python on Mac, let’s review what we’re going to discuss in this tutorial:
Installing and Updating Python on Mac
I have two pieces of news for you; one is good, the other bad. The good news is that for the sake of compatibility with legacy systems, Python 2.7 is pre-installed on your Mac, but the bad news is that Python 2.7 has been retired. Therefore, it isn’t recommended for new developments. So, if you want to take advantage of the new Python version with its many features and improvements, you need to install the latest Python alongside the version that comes pre-installed on macOS. Before we start installing the latest version of Python, let’s see why there are different versions of the same programming language. All programming languages evolve by adding new features over time. The programming language developers announce these changes and improvements by increasing the version number.
Install Python 3 as a part of the Command Line Developer Tools
To check the current version of Python that is already installed, open the Terminal application by typing command + space and then spelling out terminal and hitting return. Now, type the following command, and then hit return to see that you have Python 2.7 pre-installed on your Mac:
% python —version
Python 2.7.18
Now, try the following command to check whether or not Python 3 is installed on your Mac:
The following message will probably appear on the Terminal window,
xcode-select: note: no developer tools were found at ‘/Applications/Xcode.app’, requesting install. Choose an option in the dialog to download the command line developer tools.
And alongside the Terminal window, a dialog box will automatically appear that says this command requires the command line developer tools. First, let’s identify the command-line developer tools. To put it briefly, the command line developer tools package is a set of tools mostly used in the development process. They help run specific commands, such as make, git, python3, etc. So, although there are other ways to install Python 3.x on Mac without installing the command line developer tools, I recommend you install it because it provides a string of tools for development on Mac. To install the package, click on the Install button, and follow the steps to complete the installation process. Once the installation process is complete, rerun the previous command. Yes, Python 3.x is installed on your Mac.
% python3 —version
Python 3.8.9
Install Python 3 with the Official Installer
Downloading the latest Python version from the official Python website (python.org) is the most common (and recommended) method for installing Python on a Mac. Let’s try it out.

1. First, download an installer package from the Python website. To do that, visit https://www.python.org/downloads/ on your Mac; it detects your operating system automatically and shows a big button for downloading the latest version of Python installer on your Mac. If it doesn’t, click the macOS link and choose the latest Python release.

2. Once the download is complete, double-click the package to start installing Python. The installer will walk you through a wizard to complete the installation, and in most cases, the default settings work well, so install it like the other applications on macOS. You may also have to enter your Mac password to let it know that you agree with installing Python.
NOTE If you’re using Apple M1 Mac, you need to install Rosetta. Rosetta enables Intel-based features to run on Apple silicon Macs.

3. When the installation completes, it will open up the Python folder.

4. Let’s verify that the latest version of Python and IDLE installed correctly. To do that, double-click IDLE, which is the integrated development environment shipped with Python. If everything works correctly, IDLE shows the Python shell as follows:
5. Let’s write a simple Python code and run it in IDLE. Type the following statement, and hit the return key.


Or let’s do a basic calculation in Python as follows:
NOTE The exciting advantage of this installation method is that you can easily update an outdated Python install by downloading the latest Python installer. The new version of Python is available on your Mac once the installation is complete.
Installing Visual Studio Code on Mac
Although we can use IDLE or the terminal application for writing Python scripts, we prefer to use a powerful, extensible, and lightweight code editor rather than rigid coding environments. In this part of the tutorial, we’re going to install Visual Studio Code for Python development on macOS.
1. First, you need to download Visual Studio Code for macOS from its official website at https://code.visualstudio.com/.
2. Double-click the downloaded file to extract the archived contents.
3. Move the Visual Studio Code application to the Application folder to make it available in the macOS launchpad.
4. Launch Visual Studio Code, and then open a folder where your Python scripts exist (or create a new one). For example, create a new folder on your Desktop, and name it py_scripts , then try to open the folder on VS Code. Usually, VS Code needs your permission to access files in your Desktop folder; click OK.

Also, you may need to declare that you trust the authors of the files stored in your Desktop folder.
5. Create a new file with a .py extension. For example, create a new file, and name it prog_01.py. VS Code detects the .py extension and wants to install a Python extension.
To work with Python inside VS Code, we need to use the Python extension, which includes many useful features, such as code completion with IntelliSense, debugging, unit testing support, etc.

Install it by clicking on the Install button.
We can also install the Python extension by browsing extensions. Click on the Extensions icon on the left side of VS Code.

This will show you a list of the most popular VS Code extensions on the VS Code Marketplace. Now, we can select the Python extension and install it.

6. Once the extension is installed, you have to select a Python interpreter. Click on the Select Python Interpreter button:

Then select the recommended Python interpreter on the list.

If you have multiple Python versions installed on your Mac, it’s better to choose the latest version.
You also can select a Python interpreter using the Python: Select Interpreter command from the Command Palette. To do so, press CMD + SHIFT + P, type Python, and choose Select Interpreter.
Running Our First Python Script on Mac
Excellent, we have everything we need to write and run our Python code inside VS Code. Let’s write the following code in VS Code and then run it.
Run the code by clicking the ▶️ button at the top right corner of VS Code. First, it shows Hello, World! in the integrated terminal, then it asks your name; enter your name, and hit return. It outputs Hello <your name,> , and writes Welcome to Dataquest! on the next line.

Conclusion
In this tutorial, we learned how to install the latest version of Python on Mac, as well as updating an outdated Python version. Additionally, we learned how to install Visual Studio Code as a code editor and configure it for running Python scripts. Finally, we wrote a small Python script in VS Code and ran it successfully. In the next tutorial, we will learn about Python virtual environments and how to create and use them. Congratulations! From now on, the sky’s the limit, and you can become a great Pythonista!
If you’d like to learn more about this topic, check out Dataquest’s interactive Introduction to Python course, and our Data Analyst in Python, and Data Scientist in Python paths that will help you become job-ready in around 6 months.

About the author
Mehdi Lotfinejad
Mehdi is a Senior Data Engineer and Team Lead at ADA. He is a professional trainer who loves writing data analytics tutorials.