- 5. Using Python on a Mac¶
- 5.1. Getting and Installing MacPython¶
- 5.1.1. How to run a Python script¶
- 5.1.2. Running scripts with a GUI¶
- 5.1.3. Configuration¶
- 5.2. The IDE¶
- 5.3. Installing Additional Python Packages¶
- 5.4. GUI Programming on the Mac¶
- 5.5. Distributing Python Applications on the Mac¶
- 5.6. Other Resources¶
- Installing Python 3 on Mac OS X¶
- Doing it Right¶
- Working with Python 3¶
- Pipenv & Virtual Environments¶
- O’Reilly Book
- Как установить Python 3 на macOS в качестве версии по умолчанию
- 1. Установите pyenv
- 2. Установите Python
- 3. Установите глобальное значение по умолчанию
- Успешный результат
- Среда выполнения Python
- Чего не стоит делать
- Что можно попробовать
- Использовать Python 3 по умолчанию для macOS
- Доверить управление Homebrew
- Что делать, если нам все еще нужен Python 2?
- Не забудьте обновить pip до версии pip3!
- Заключение
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 since version 10.8 comes with Python 2.7 pre-installed by Apple. If you wish, 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.9 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 (http://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 http://undefined.org/python/#py2app.
5.6. Other Resources¶
The MacPython mailing list is an excellent support resource for Python users and developers on the Mac:
Another useful resource is the MacPython wiki:
Источник
Installing Python 3 on Mac OS X¶
Mac OS X comes with Python 2.7 out of the box.
You do not need to install or configure anything else to use Python 2. These instructions document the installation of Python 3.
The version of Python that ships with OS X is great for learning, but it’s not good for development. The version shipped with OS X may be out of date from the official current Python release, which is considered the stable production version.
Doing it Right¶
Let’s install a real version of Python.
Before installing Python, you’ll need to install GCC. GCC can be obtained by downloading Xcode, the smaller Command Line Tools (must have an Apple account) or the even smaller OSX-GCC-Installer package.
If you already have Xcode installed, do not install OSX-GCC-Installer. In combination, the software can cause issues that are difficult to diagnose.
If you perform a fresh install of Xcode, you will also need to add the commandline tools by running xcode-select —install on the terminal.
While OS X comes with a large number of Unix utilities, those familiar with Linux systems will notice one key component missing: a package manager. Homebrew fills this void.
To install Homebrew, open Terminal or your favorite OS X terminal emulator and run
The script will explain what changes it will make and prompt you before the installation begins. Once you’ve installed Homebrew, insert the Homebrew directory at the top of your PATH environment variable. You can do this by adding the following line at the bottom of your
If you have OS X 10.12 (Sierra) or older use this line instead
Now, we can install Python 3:
This will take a minute or two.
Homebrew installs pip pointing to the Homebrew’d Python 3 for you.
Working with Python 3¶
At this point, you have the system Python 2.7 available, potentially the Homebrew version of Python 2 installed, and the Homebrew version of Python 3 as well.
will launch the Homebrew-installed Python 3 interpreter.
will launch the Homebrew-installed Python 2 interpreter (if any).
will launch the Homebrew-installed Python 3 interpreter.
If the Homebrew version of Python 2 is installed then pip2 will point to Python 2. If the Homebrew version of Python 3 is installed then pip will point to Python 3.
The rest of the guide will assume that python references Python 3.
Pipenv & Virtual Environments¶
The next step is to install Pipenv, so you can install dependencies and manage virtual environments.
A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.
For example, you can work on a project which requires Django 1.10 while also maintaining a project which requires Django 1.8.
This page is a remixed version of another guide, which is available under the same license.
This opinionated guide exists to provide both novice and expert Python developers a best practice handbook to the installation, configuration, and usage of Python on a daily basis.
O’Reilly Book
This guide is now available in tangible book form!
All proceeds are being directly donated to the DjangoGirls organization.
Источник
Как установить Python 3 на macOS в качестве версии по умолчанию
Есть несколько способов начать работу с Python 3 на macOS, однако не все они одинаково хороши. Сегодня мы рассмотрим, как правильно настроить среду, не нарушая ничего, встроенного в операционную систему macOS.
1. Установите pyenv
Использование неправильного решения может привести к неверному представлению о том, что выбор загружаемой версии Python зависит от псевдонимов в оболочке.
Как нам перестать заботиться о том, какая версия Python используется по умолчанию? Нужно использовать pyenv. Это инструмент для управления несколькими версиями Python. Он простой и вполне соответствует традициям Unix: предназначен для решения одной задачи, и решает ее хорошо.
Хотя доступны и другие варианты установки, проще всего начать следующим образом:
2. Установите Python
Теперь давайте установим последнюю версию Python (здесь указана версия 3.7.3, однако на данный момент широко используется версия 3.8 и доступна версия 3.9):
3. Установите глобальное значение по умолчанию
Теперь, когда Python 3 установлен через pyenv, мы хотим установить его как нашу версию по умолчанию (глобально) для сред pyenv:
Сила pyenv основана на том, что он контролирует путь нашей оболочки. Чтобы он работал правильно, нам нужно добавить следующее в наш файл конфигурации (мы использовали .zshrc, а вам, возможно, подойдет .bash_profile):
После этой команды наш файл (.zshrc для zsh или .bash_profile для Bash) должен включать следующие строки:
Теперь мы точно знаем, что используем Python 3.7.3, и pip будет обновляться вместе с ним без какой-либо ручной настройки и конфликтов между версиями. Использование менеджера версий (pyenv) позволяет нам легко регулировать будущие обновления, не беспокоясь о том, какую версию Python мы используем в данный момент.
Успешный результат
Освоив этот рабочий процесс, вы сможете использовать pyenv для управления несколькими версиями Python.
Для управления зависимостями также важно использовать виртуальные среды. Тут нам пригодятся такие встроенные библиотеки, как venv и virtualenvwrapper.
Среда выполнения Python
Теперь, когда мы разобрались с версиями Python, можно углубиться в вопрос, почему эта проблема сбивает с толку так много людей.
Версия Python, поставляемая с macOS, сильно устарела по сравнению с тем, что Python рекомендует использовать для разработки. Как отмечает XKCD, размышления о выборе среды выполнения Python иногда могут быть до смешного сложными:
Многие пользователи держат десятки интерпретаторов Python на своих компьютерах, хотя понятия не имеют, как эффективно ими управлять.
Слишком часто люди просто загружают последнюю версию Python, помещают ее в свою переменную $PATH и на этом всё (или используют команду brew install python3 , которая делает примерно то же самое). Это может привести к поломкам и неисправностям, которые будет весьма сложно исправить.
Чего не стоит делать
Можно подумать, что, чтобы сделать Python 3 на macOS версией по умолчанию, нужно заменить старую версию и на новую:
Этот шаблон соответствует тому, что обычно делает /usr/bin/ между основными выпусками Python, однако это неправильный ход:
К счастью, macOS не дает сломать систему непродуманными действиями. Дальнейшие исследования вопроса показывают, что описанный выше способ не следует применять.
Что можно попробовать
Теперь, когда мы знаем, чего не следует делать, давайте посмотрим, что сделать можно. Когда мы думаем об общих шаблонах установки приложений в macOS, есть несколько вариантов.
Использовать Python 3 по умолчанию для macOS
На веб-сайте Python есть установщик macOS Python 3, который мы можем загрузить и использовать. Если мы воспользуемся установкой пакета, python3 будет доступен в /usr/local/bin/.
Поскольку двоичный файл Python, хранящийся в /usr/bin/, не может быть изменен, необходимы алиасы (псевдонимы). Что хорошо в псевдониме, так это то, что он специфичен для нашей оболочки командной строки. Поскольку по умолчанию мы используем zsh, мы помещаем в файл .zshrc следующее:
Если по умолчанию вы используете оболочку Bash, вы можете добавить следующий текст в свой .bashrc :
Эта стратегия работает, но она не идеальна для будущих обновлений Python. Это означает, что нам придется регулярно проверять сайт и загружать новые файлы, поскольку Python не включает в себя способ обновления из командной строки.
Доверить управление Homebrew
Проект Homebrew предоставляет бесплатный менеджер пакетов для macOS, на который полагаются многие люди. Он имеет открытый исходный код. Этот менеджер пакетов дает пользователям Apple возможности, аналогичные возможностям apt-get или yum.
Если вы являетесь пользователем Homebrew, возможно, у вас уже установлен Python. Чтобы быстро проверить это, запустите конвейер команд:
Если в качестве результата вы получите python, значит, он установлен. Но какая это версия? Давайте проверим:
Отлично! Мейнтейнеры Homebrew обновили Python bottle (бинарный пакет), чтобы он указывал на последний релиз. Поскольку мейнтейнеры Homebrew более ответственны в отношении обновления релиза, чем большинство из нас, мы можем использовать версию Python 3 от Homebrew с помощью следующей команды:
Теперь нам нужно, чтобы наш алиас указывал на копию Python, которой управляет Homebrew:
Чтобы убедиться, что приведенный выше путь указывает на то место, куда Homebrew установил Python в нашей среде, мы можем запустить brew info python и поискать информацию о пути.
Этот метод использования Homebrew для управления нашей средой Python является хорошей отправной точкой.
Что делать, если нам все еще нужен Python 2?
Для любого новичка в Python имеет смысл начинать сразу с Python 3. Но те из нас, кому все еще нужен Python 2 – например, для участия в проекте, где есть только Python 2, – могут продолжать использовать версию Python, доступную в macOS по умолчанию (путь — /usr/bin/python):
Homebrew настолько хорош, что даже предлагает другую формулу для Python 2:
Чтобы вернуться к использованию версии Python, которая установлена в системе по умолчанию, в любой момент можно удалить псевдонимы из файла конфигурации нашей оболочки.
Не забудьте обновить pip до версии pip3!
pip – это дефолтный менеджер пакетов Python. Хотя мы изменили нашу дефолтную команду python на третью версию, нужно также отдельно задать псевдоним нашей команде pip (если у нас предыдущая версия).
Для начала нужно проверить, какая, собственно, у нас версия:
Чтобы устанавливать пакеты, наверняка совместимые с нашей новой версией Python, мы используем еще один алиас, указывающий на совместимую версию pip.
Поскольку в данной ситуации мы используем Homebrew в качестве менеджера пакетов, мы знаем, что он установил pip3 при установке Python 3. Путь по умолчанию должен быть таким же, как и в Python 3, но мы можем проверить это, попросив оболочку найти его:
Теперь, когда мы точно знаем местоположение, мы добавим его в наш файл конфигурации оболочки, как мы это делали раньше:
Наконец, мы можем проверить, что запущенный pip указывает на pip3. Для этого нужно открыть новую оболочку или перезагрузить текущую и посмотреть, на сто указывает псевдоним:
Мы можем избежать использования Homebrew для обновления pip, но для этого потребуется гораздо более подробное руководство, основанное на документации Python.
Заключение
Если вы только начинаете разработку на Python на macOS, выполните необходимые настройки, чтобы с самого начала использовать правильную версию Python.
Установка Python 3 с Homebrew или без него и использование псевдонима позволят вам начать программировать, но в долгосрочной перспективе это не лучшая стратегия.
Использование pyenv — простое решение для управления версиями. Оно станет отличной отправной точкой.
Источник