Python �������������� ��� mac os

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.

Читайте также:  Апгрейд ноутбука windows 10

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:

Источник

4. Использование Python на Macintosh¶

Python на Macintosh под управлением Mac OS X в принципе очень похож на Python на любой другой платформе Unix, но есть ряд дополнительных функций, таких как IDE и диспетчер пакетов, на которые стоит обратить внимание.

4.1. Получение и установка MacPython¶

Mac OS X 10.8 поставляется с Python 2.7, предустановленным Apple. Если нужно, вы можете установить самую последнюю версию Python 3 с веб-сайта Python. Здесь доступна текущая «универсальная двоичная» сборка Python, которая изначально работает на новом процессоре Intel и устаревших процессорах PPC Mac.

После установки вы получите несколько вещей:

  • Папка Python 3.8 в папке Applications . Здесь вы найдете IDLE, среду разработки, которая является стандартной частью официальных дистрибутивов Python; и PythonLauncher, который обрабатывает скрипты Python двойным щелчком из Finder.
  • Фреймворк /Library/Frameworks/Python.framework , который включает исполняемый файл Python и библиотеки. Установщик добавляет это местоположение в путь к вашей оболочке. Чтобы удалить MacPython, вы можете просто удалить эти три вещи. Символьная ссылка на исполняемый файл Python находится в /usr/local/bin/.

Предоставленная Apple сборка Python установлена в /System/Library/Frameworks/Python.framework и /usr/bin/python соответственно. Вы никогда не должны изменять или удалять их, поскольку они контролируются Apple и используются программным обеспечением Apple или сторонними производителями. Помните, что если вы решите установить более новую версию Python с официального сайта, у вас будут две разные, но функциональные установки Python на вашем компьютере, поэтому важно, чтобы ваши пути и способы использования соответствовали тому, что вам нужно.

IDLE включает меню справки, которое позволяет получить доступ к документации Python. Если вы новичок в Python, вам следует начать читать введение в этот документ.

Если вы знакомы с Python на других платформах Unix, вам следует прочитать раздел о запуске сценариев Python из оболочки Unix.

4.1.1. Как запустить Python скрипт¶

Лучший способ начать работу с Python в Mac OS X — использовать интегрированную среду разработки IDLE, см. раздел IDE и использовать меню «Help» во время работы IDE.

Если вы хотите запускать скрипты Python из командной строки окна терминала или из Finder, вам сначала понадобится редактор для создания вашего скрипта. Mac OS X поставляется с рядом стандартных редакторов командной строки Unix, среди которых vim и emacs. Если вам нужен редактор, более похожий на Mac, BBEdit или TextWrangler от Bare Bones Software — хороший выбор, как и TextMate. Другие редакторы включают Gvim и Aquamacs.

Читайте также:  Не открывается установочный файл exe windows 10

Чтобы запустить сценарий из окна терминала, вы должны убедиться, что /usr/local/bin находится в пути поиска вашей оболочки.

Чтобы запустить сценарий из Finder, у вас есть два варианта:

  • Перетащите его на PythonLauncher
  • Выберите PythonLauncher в качестве приложения по умолчанию, чтобы открыть ваш скрипт (или любой другой скрипт .py) через информационное окно Finder, и дважды щелкните его. У PythonLauncher есть различные настройки для управления запуском вашего скрипта. Опциональное перетаскивание позволяет вам изменить их для одного вызова или использовать его меню Preferences, чтобы изменить вещи глобально.

4.1.2. Запуск скриптов с графическим интерфейсом¶

В более старых версиях Python есть одна особенность Mac OS X, о которой вам нужно знать: программы, которые взаимодействуют с оконным менеджером Aqua (другими словами, всё, что имеет графический интерфейс), должны запускаться особым образом. Для запуска таких сценариев используйте pythonw вместо python.

С Python 3.8 вы можете использовать python или pythonw.

4.1.3. Конфигурация¶

Python в OS X учитывает все стандартные переменные среды Unix, такие как PYTHONPATH , но установка этих переменных для программ, запускаемых из Finder, нестандартна, поскольку Finder не считывает ваши .profile или .cshrc при запуске. Вам необходимо создать файл

/.MacOSX/environment.plist . Подробности см. в техническом документе Apple QA1067.

Дополнительные сведения об установке пакетов Python в MacPython см. в разделе Установка дополнительных пакетов Python .

4.2. IDE¶

MacPython поставляется со стандартной средой разработки IDLE. Хорошее введение в использование IDLE можно найти на ресурсе.

4.3. Установка дополнительных пакетов Python¶

Есть несколько способов установить дополнительные пакеты Python:

  • Пакеты могут быть установлены через стандартный режим Python distutils ( python setup.py install ).
  • Многие пакеты также можно установить через расширение setuptools или обёртку pip.

4.4. Программирование графического интерфейса пользователя на Mac¶

Существует несколько вариантов создания приложений с графическим интерфейсом пользователя на Mac с помощью Python.

PyObjC — это привязка Python к платформе Apple Objective-C/Cocoa, которая является основой большинства современных разработок для Mac. Информация о PyObjC доступна по адресу https://pypi.org/project/pyobjc/.

Стандартный набор инструментов Python GUI — tkinter , основан на кроссплатформенном наборе инструментов Tk (https://www.tcl.tk). Версия Tk для Aqua поставляется в комплекте с OS X от Apple, а последнюю версию можно загрузить и установить с https://www.activestate.com; его также можно собрать из исходников.

wxPython — ещё один популярный кроссплатформенный набор инструментов для графического интерфейса, который изначально работает в Mac OS X. Пакеты и документация доступны по адресу https://www.wxpython.org.

PyQt — ещё один популярный кроссплатформенный набор инструментов для графических интерфейсов, который изначально работает в Mac OS X. Дополнительную информацию можно найти на https://riverbankcomputing.com/software/pyqt/intro.

4.5. Распространение приложений Python на Mac¶

Стандартный инструмент для развертывания автономных приложений Python на Mac — py2app. Дополнительную информацию об установке и использовании py2app можно найти на сайте.

4.6. Другие источники¶

Список рассылки MacPython — отличный ресурс поддержки для пользователей Python и разработчиков на Mac.

Источник

The core of extensible programming is defining functions. Python allows mandatory and optional arguments, keyword arguments, and even arbitrary argument lists. More about defining functions in Python 3

Lists (known as arrays in other languages) are one of the compound data types that Python understands. Lists can be indexed, sliced and manipulated with other built-in functions. More about lists in Python 3

Calculations are simple with Python, and expression syntax is straightforward: the operators + , — , * and / work as expected; parentheses () can be used for grouping. More about simple math functions in Python 3.

Experienced programmers in any other language can pick up Python very quickly, and beginners find the clean syntax and indentation structure easy to learn. Whet your appetite with our Python 3 overview.

Python knows the usual control flow statements that other languages speak — if , for , while and range — with some of its own twists, of course. More control flow tools in Python 3

Python is a programming language that lets you work quickly and integrate systems more effectively. Learn More

Читайте также:  Trendnet tew 423pi драйвер windows 10

Get Started

Whether you’re new to programming or an experienced developer, it’s easy to learn and use Python.

Download

Python source code and installers are available for download for all versions!

Documentation for Python’s standard library, along with tutorials and guides, are available online.

Looking for work or have a Python related position that you’re trying to hire for? Our relaunched community-run job board is the place to go.

Источник

Installing Python 2 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. Having said that, I would strongly recommend that you install the tools and libraries described in the next section before you start building Python applications for real-world use. In particular, you should always install Setuptools, as it makes it much easier for you to install and manage other third-party Python libraries.

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 a C compiler. The fastest way is to install the Xcode Command Line Tools by running xcode-select —install . You can also download the full version of Xcode from the Mac App Store, or the minimal but unofficial 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 decent 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

Now, we can install Python 2.7:

Because python@2 is a “keg”, we need to update our PATH again, to point at our new installation:

Homebrew names the executable python2 so that you can still run the system Python via the executable python .

Setuptools & Pip¶

Homebrew installs Setuptools and pip for you.

Setuptools enables you to download and install any compliant Python software over a network (usually the Internet) with a single command ( easy_install ). It also enables you to add this network installation capability to your own Python software with very little work.

pip is a tool for easily installing and managing Python packages, that is recommended over easy_install . It is superior to easy_install in several ways, and is actively maintained.

Virtual Environments¶

A Virtual Environment (commonly referred to as a ‘virtualenv’) 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.

To start using this and see more information: Virtual Environments docs.

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.

Источник

Оцените статью