5. 在 macOS 上使用 Python

本文档旨在为您于 Mac 电脑上开始使用 Python 前提供您必须了解的 macOS 平台之特有行为。在运行了 macOS 的 Mac 电脑上使用 Python 与在其他 Unix 家族平台电脑上面使用 Python 的体验非常相近,但在 Python 安装及部分特性上仍存有些许差异。

有多种途径可为 macOS 获取 Python 。多家软件分发源均提供最新版 Python 的预编译版本。本文档的多数内容描述的是由 CPython 发布团队于 python.org 网站 中提供下载的 Python 版本。参见 其他发行版 获取其他选择。

5.1. 使用来自 python.org 的 macOS 版 Python

5.1.1. 安装步骤

For current Python versions (other than those in security status), the release team produces a Python for macOS installer package for each new release. A list of available installers is provided on the macOS downloads page. We recommend using the most recent supported Python version where possible. Current installers provide a universal2 binary build of Python which runs natively on all Macs (Apple Silicon and Intel) that are supported by a wide range of macOS versions, currently typically from at least macOS 10.15 Catalina on.

The downloaded file is a standard macOS installer package file (.pkg). File integrity information (such as checksum, size, and Sigstore signature) for each file is included on the release download page. Installer packages and their contents are signed and notarized with Python Software Foundation Apple Developer ID certificates to meet macOS Gatekeeper requirements.

For a default installation, double-click on the downloaded installer package file. This should launch the standard macOS Installer app and display the first of several installer steps.

../_images/mac_installer_01_introduction.png

点击 Continue 按钮将显示安装程序的 Read Me。 在其他重要信息之外,Read Me 文档会写明将要安装的 Python 版本以及它所支持的 macOS 版本。 你可能需要滚动窗口来阅读整个文件。 在默认情况下,该 Read Me 也会被安装在 /Applications/Python 3.16/ 中并可供随时阅读。

../_images/mac_installer_02_readme.png

点击 继续 按钮将会显示 Python 软件及其他随附软件的授权许可。你需要选择 同意 该许可证才能继续下一步安装。同样,许可证日后也会安装在磁盘中以供随时阅读。

../_images/mac_installer_03_license.png

接受许可证条款后,下一步是选择您的安装类型。在大多数情况下,默认的标准安装操作就是最适合您的安装类型。

../_images/mac_installer_04_installation_type.png

By pressing the Customize button, you can choose to omit or select certain package components of the installer. Click on each package name to see a description of what it installs. For details of the optional free-threaded feature, which is installed by default, see 安装自由线程二进制文件.

../_images/mac_installer_05_custom_install.png

不论您选择接受默认安装配置还是自定义安装配置,点击 安装 按钮即可开始安装过程。您可能会被要求提供安装软件所需的必要权限。您需要提供拥有 Administrator (管理员)权限的 macOS 用户名和密码,因为 Python 会面向电脑中的所有用户安装。

安装完成后会显示 概览 窗口。

../_images/mac_installer_06_summary.png

双击 Install Certificates.command 图标或 /Applications/Python 3.16/ 窗口中的文件来完成安装。

../_images/mac_installer_07_applications.png

这会开启一个临时的 Terminal 命令行窗口,使用新安装的 Python 下载并安装SSL根证书供其使用。

../_images/mac_installer_08_install_certificates.png

如果终端窗口中显示 Successfully installed certifiupdate complete,则安装完成。 请关闭该终端窗口和安装程序窗口。

使用默认安装配置会安装下列内容:

  • 你的 Applications 文件夹中的 Python 3.16 子文件夹。 你将在这里找到 IDLE,这是作为官方 Python 发行版标准组件的开发环境;以及 Python Launcher,它负责处理在 macOS Finder 中双击 Python 脚本的操作。

  • 一个框架 /Library/Frameworks/Python.framework,它包括 Python 可执行文件和库。 安装程序会将此位置添加到你的 shell 路径。 要卸载 Python,你可以移除这三样东西。 指向 Python 可执行文件的符号链接将位于 /usr/local/bin/

备注

最近几个版本的 macOS 都包括一个 python3 命令 /usr/bin/python3,它链接到一个供 Apple 开发工具 XcodeCommand Line Tools for Xcode 使用的通常较老旧且不完整的 Python 版本。 你绝不应该修改或试图删除此安装版,因为它是由 Apple 控制且由 Apple 提供的或第三方的软件所使用。 如果你选择安装一个来自 python.org 的更新的 Python 版本,在你的计算机上将有两个不相同但均能正常运行的 Python 安装版共存。 默认安装程序选项应当会确保使用它的 python3 而不是系统的 python3

5.1.2. 如何运行 Python 脚本

有两种方式可以唤起 Python 解释器。 如果你熟悉如何在终端窗口中使用 Unix shell,你可以唤起 python3.16python3 并可选择带一个或多个命令行选项(见 命令行与环境 中的说明)。 Python 教程也包含了一个有关 通过 shell 交互式地使用 Python 的实用章节。

你也可以通过集成开发环境即 IDE 来唤起解释器。 IDLE --- Python 编辑器和 shell 是一个包括在标准 Python 发行版中的具有基础功能的编辑器和解释器环境。 IDLE 还包括一个 Help 菜单允许你访问 Python 文档。 如果你是完全的 Python 新手,你可以阅读此文档中的入门教程。

还有许多其他可用的编辑器和 IDE,请参阅 编辑器和集成开发环境 了解详情。

要在终端窗口运行一个 Python 脚本,你可以在唤起解释器时附带脚本文件名:

python3.16 myscript.py

要从 Finder (访达)运行你的脚本,你有两种选择:

  • 将其拖拽到 Python Launcher

  • 选择 Python Launcher 作为通过 Finder Info 窗口打开你的脚本(或任何 .py 脚本)和双击它时的默认应用程序。 Python Launcher 具有多个首选项来控制脚本的启动方式。 选项拖拽允许你为单次唤起更改这些首选项,或使用其 Preferences 菜单进行全局性的更改。

请注意从 macOS Finder 直接运行脚本可能产生与从终端窗口运行时不同的结果,因为脚本将不是在通常的包括了 shell 配置文件中所有环境变量的 shell 环境中运行。 因此,就如使用任何其他脚本或程序一样,请注意确认你想要运行的到底是什么。

5.2. 其他发行版

除了标准 python.org macOS 安装程序,还有一些针对 macOS 的包括附加功能的第三方发行版。 以下是一些受欢迎的发行版及其关键特性:

ActivePython

具有多平台兼容性的安装器,文档

Anaconda

流行的科学模块(如 numpy, scipy 和 pandas)以及 conda 包管理器。

Homebrew

针对 macOS 的包管理器包括多个 Python 版本和许多基于 Python 的第三方包(包括 numpy, scipy 和 pandas)。

MacPorts

另一个针对 macOS 的包括多个 Python 版本和许多基于 Python 的第三方软件包的包管理器。 可能包括 Python 的预构建版和许多用于较旧版本 macOS 的软件包。

请注意这些发行版可能不包括 Python 或其他库的最新版本,并且不被核心 Python 团队所维护或支持。

5.3. 安装额外的 Python 包

请参阅 Python Packaging User Guide 了解详情。

5.4. GUI 编程

使用 Python 在 Mac 上构建 GUI 应用程序有多种选择。

标准的 Python GUI 工具包是 tkinter,基于跨平台的 Tk 工具包 (https://www.tcl.tk)。 安装器包括了一个 macOS 原生版本的 Tk。

PyObjC 是一个针对 Apple 的 Objective-C/Cocoa 框架的 Python 绑定。 有关 PyObjC 的信息可从 pyobjc 获取。

有多个替代性的 macOS GUI 工具包可供使用,包括:

  • PySide: Qt GUI 工具包 的官方 Python 绑定。

  • PyQt: Qt 的另一款 Python 绑定。

  • Kivy: 一款支持桌面和移动平台的跨平台 GUI 工具包。

  • Toga: BeeWare 项目 的一部分;支持桌面、移动设备、Web 和控制台应用。

  • wxPython: 一款支持桌面操作系统的跨平台工具包。

5.5. 进阶主题

5.5.1. 安装自由线程二进制文件

Added in version 3.13.

在 3.15 版本发生变更: 自由线程支持现在将默认被安装。

The python.org Python for macOS installer package installs, by default, an additional build of Python 3.16 that supports free threading (running with the global interpreter lock disabled). Check the release page on python.org for possible updated information.

The free-threaded mode is working and continues to be improved, but there is some additional overhead in single-threaded workloads compared to the regular build. Additionally, third-party packages, in particular ones with an extension module, may not be ready for use in a free-threaded build, and will re-enable the GIL. As of Python 3.15, free-threading support is installed by default. It is packaged as a separate install option, which can be deselected by clicking the Customize button on the Installation Type step of the installer as described above.

../_images/mac_installer_09_custom_install_free_threaded.png

If the box next to the Free-threaded Python package name is checked (as it is by default), a separate PythonT.framework will also be installed alongside the normal Python.framework in /Library/Frameworks. This configuration allows a free-threaded Python 3.16 build to co-exist on your system with a traditional (GIL only) Python 3.16 build with minimal risk while installing or testing. This installation layout may change in future releases.

已知的注意事项和限制:

  • The UNIX command-line tools package, which is selected by default, will install links in /usr/local/bin for python3.16t, the free-threaded interpreter, and python3.16t-config, a configuration utility which may be useful for package builders. Since /usr/local/bin is typically included in your shell PATH, in most cases no changes to your PATH environment variable should be needed to use python3.16t.

  • 对于本发布版,Shell profile updater 软件包和 /Applications/Python 3.16/ 中的 Update Shell Profile.command 均不支持自由线程的软件包。

  • 自由线程构建版和传统构建版具有不同的搜索路径和不同的 site-packages 目录,因此在默认情况下,如果你需要让某个包在两个构建版中均可用,可能需要在两版中都安装。 自由线程的软件包将安装单独的 pip 来配合 python3.16t 使用。

    • 不带 venv 地使用 pip 来安装软件包:

      python3.16t -m pip install <package_name>
  • 在操作多个 Python 环境时,创建和使用虚拟环境 通常是最安全和便捷的方式。 这可以避免可能的命令名称冲突和究竟是哪个 Python 正在被使用的困惑:

    python3.16t -m venv <venv_name>

    然后执行 activate

  • 要运行 IDLE 的自由线程版本:

    python3.16t -m idlelib
  • 两个构建版中的解释器响应相同的 PYTHON 环境变量 可能导致预料之外的结果,举例来说,如果你在 shell 配置文件中设置了 PYTHONPATH 的话。 如有必要,可以使用像 -E 这样的 命令行选项 来忽略这些环境变量。

  • 自由线程构建版会链接安装在传统框架中的第三方共享库,如 OpenSSLTk。 这意味着两个构建版还会共享同一个由 Install Certificates.command 脚本所安装的信任证书,因此它只须运行一次。

  • 如果你不能依赖 /usr/local/bin 中指向 python.org 自由线程 python3.16t 的链接(举例来说,如果你想在其中安装你自己的版本或者其他发行版要这样做),你可以显式设置你的 PATH 环境变量以包括 PythonT 框架的 bin 目录:

    export PATH="/Library/Frameworks/PythonT.framework/Versions/3.16/bin":"$PATH"

    传统框架安装版默认会做类似的事情,但 Python.framework 除外。 请注意将两个框架的 bin 目录都放入 PATH 在存在重名如 python3.16 时可能会导致混淆;实际是使用哪一个取决于它们在 PATH 中的出现顺序。 which python3.xwhich python3.xt 命令可以显示正在使用哪个路径。 使用虚拟环境有助于避免这样的歧义。 另一种选项是创建一个 shell alias 指向特定解释器,例如:

    alias py3.16="/Library/Frameworks/Python.framework/Versions/3.16/bin/python3.16"
    alias py3.16t="/Library/Frameworks/PythonT.framework/Versions/3.16/bin/python3.16t"

5.5.2. 使用命令行安装

If you want to use automation to install the python.org installer package (rather than by using the familiar macOS Installer GUI app), the macOS command line installer utility lets you select non-default options, too. If you are not familiar with installer, it can be somewhat cryptic (see man installer for more information). As an example, the following shell snippet shows one way to do it, using the 3.16.0b2 release and deselecting the free-threaded interpreter option:

RELEASE="python-3.160b2-macos11.pkg"

# download installer pkg
curl -O https://www.python.org/ftp/python/3.16.0/${RELEASE}

# create installer choicechanges to customize the install:
#    disable the PythonTFramework-3.16 package
#    while accepting the other defaults (install all other packages)
cat > ./choicechanges.plist <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
        <dict>
                <key>attributeSetting</key>
                <integer>0</integer>
                <key>choiceAttribute</key>
                <string>selected</string>
                <key>choiceIdentifier</key>
                <string>org.python.Python.PythonTFramework-3.16</string>
        </dict>
</array>
</plist>
EOF

sudo installer -pkg ./${RELEASE} -applyChoiceChangesXML ./choicechanges.plist -target /

在默认安装之后,你可以这样测试两个构建版是否都可用:

$ # test that the free-threaded interpreter was installed if the Unix Command Tools package was enabled
$ /usr/local/bin/python3.16t -VV
Python 3.16.0b2 free-threading build (v3.16.0b2:3a83b172af, Jun  5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]
$ #    and the traditional interpreter
$ /usr/local/bin/python3.16 -VV
Python 3.16.0b2 (v3.16.0b2:3a83b172af, Jun  5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)]
$ # test that they are also available without the prefix if /usr/local/bin is on $PATH
$ python3.16t -VV
Python 3.16.0b2 free-threading build (v3.16.0b2:3a83b172af, Jun  5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]
$ python3.16 -VV
Python 3.16.0b2 (v3.16.0b2:3a83b172af, Jun  5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)]

备注

当前的 python.org 安装器只会安装到固定位置如 /Library/Frameworks/, /Applications/usr/local/bin。 你不能使用 installer -domain 选项来安装到其他位置。

5.5.3. 分发 Python 应用程序

有一系列工具可将你的 Python 代码转换为独立发布的应用程序:

  • py2app: 支持基于 Python 项目创建 macOS .app 软件包。

  • Briefcase: BeeWare 项目 的一部分;一款支持在 macOS 上创建 .app 捆绑包,并能管理签名和公证的跨平台打包工具。

  • PyInstaller: 一款可创建单独文件或文件夹作为可分发包的跨平台打包工具。

5.5.4. App Store 合规性

在 macOS App Store 中提交发布的 app 必须通过 Apple 的 app 审核进程。 此进程包括一组在所提交的应用程序包中自动检查有问题代码的验证规则。

Python 标准库包含了一些已知会违反这些自动规则的代码。 虽然这些违规情况看来是属于误报,但 Apple 的审核规则是不可挑战的。 因此,有必要修改 Python 标准库以便 app 能够通过 App Store 的审核。

Python 源代码树包含 一个补丁文件 可移除所有已知的会导致 App Store 审核过程出现问题的代码。 这个补丁会在 CPython 配置了 --with-app-store-compliance 选项时自动应用。

这个补丁对于在 Mac 上使用 CPython 并不是必需的;如果你是在 macOS App Store 以外 的地方发布 app 它也不是必需的。 它 只有 在你使用 macOS App Store 作为发布渠道时才是必需的。

5.6. 其它资源

python.org Help 页面 包含许多有用资源的链接。 Pythonmac-SIG 邮件列表 是另一个专门针对 Mac 上的 Python 用户和开发者的支持资源。