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. 安装步骤

对于 当前 Python 版本 (处于 security 状态的除外),发布团队为每个新发布版制作了 macOS 版 Python 安装程序包。 可以在 这里 查看安装程序列表。 我们推荐尽可能使用最新的受支持的 Python 版本。 当前安装程序提供了可原生运行于所有 Mac (Apple Silicon 和 Intel) 并支持主流 macOS 版本的 universal2 二进制 Python 构建版,目前通常至少支持到 macOS 10.13 High Sierra

您下载的文件是一个标准的 macOS 安装器包文件(.pkg)。我们为每个文件都提供用于校验文件完整性的资料(校验码、文档大小、签名等),随附于下载页面中。安装器包及其内容均使用 Python Software Foundation 的 Apple 开发者 ID 证书签名及公证,符合 macOS 门禁(Gatekeeper)要求

如欲使用默认预设安装配置,请直接双击您所下载的安装包文件。这将开启 macOS 内置的标准安装器软件,窗口中会显示安装步骤的第一步。

../_images/mac_installer_01_introduction.png

点击 继续 按钮后会开启安装包中自带的 Read Me 文档。文档里面有一些重要内容,但也记录了您将要安装的 Python 版本,此外也记录了本软件所支持的 macOS 版本。您可能需要滚动窗口才能阅读完整的文件。在默认配置下,该 Read Me 文档也会安装在 /Applications/Python 3.13/ 路径中以供随时阅读。

../_images/mac_installer_02_readme.png

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

../_images/mac_installer_03_license.png

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

../_images/mac_installer_04_installation_type.png

若您点击左下角的 自定义 按钮,您可以选择或取消选择安装包当中的部分组件。点击列表中的每一个项目可以了解该组件包会安装什么东西。若您想安装实验性可选的自由线程特性,请参见 安装自由线程二进制文件

../_images/mac_installer_05_custom_install.png

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

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

../_images/mac_installer_06_summary.png

浏览至 /Applications/Python 3.13/ 文件夹窗口,双击 Install Certificates.command 图标或文件以完成最后的安装步骤。

../_images/mac_installer_07_applications.png

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

../_images/mac_installer_08_install_certificates.png

如果 Successfully installed certifiupdate complete 字样出现在了终端的窗口中,那么安装就顺利完成。您可以关闭该终端窗口和安装器窗口。

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

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

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

备注

Recent versions of macOS include a python3 command in /usr/bin/python3 that links to a usually older and incomplete version of Python provided by and for use by the Apple development tools, Xcode or the Command Line Tools for Xcode. You should never modify or attempt to delete this installation, as it is Apple-controlled and is used by Apple-provided or third-party software. If you choose to install a newer Python version from python.org, you will have two different but functional Python installations on your computer that can co-exist. The default installer options should ensure that its python3 will be used instead of the system python3.

5.1.2. 如何运行 Python 脚本

There are two ways to invoke the Python interpreter. If you are familiar with using a Unix shell in a terminal window, you can invoke python3.13 or python3 optionally followed by one or more command line options (described in 命令行与环境). The Python tutorial also has a useful section on using Python interactively from a shell.

You can also invoke the interpreter through an integrated development environment. IDLE is a basic editor and interpreter environment which is included with the standard distribution of Python. IDLE includes a Help menu that allows you to access Python documentation. If you are completely new to Python, you can read the tutorial introduction in that document.

There are many other editors and IDEs available, see 编辑器和集成开发环境 for more information.

To run a Python script file from the terminal window, you can invoke the interpreter with the name of the script file:

python3.13 myscript.py

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

  • 将其拖拽到 Python Launcher

  • Select Python Launcher as the default application to open your script (or any .py script) through the Finder Info window and double-click it. Python Launcher 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.

Be aware that running the script directly from the macOS Finder might produce different results than when running from a terminal window as the script will not be run in the usual shell environment including any setting of environment variables in shell profiles. And, as with any other script or program, be certain of what you are about to run.

5.2. 其他发行版

Besides the standard python.org for macOS installer, there are third-party distributions for macOS that may include additional functionality. Some popular distributions and their key features:

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: (试验性功能)

备注

本节中描述的所有内容都是试验性的,它们预计会在未来的发布版中发生改变。

The python.org Python for macOS installer package can optionally install an additional build of Python 3.13 that supports PEP 703, the experimental free-threading feature (running with the global interpreter lock disabled). Check the release page on python.org for possible updated information.

Because this feature is still considered experimental, the support for it is not installed by default. It is packaged as a separate install option, available 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, a separate PythonT.framework will also be installed alongside the normal Python.framework in /Library/Frameworks. This configuration allows a free-threaded Python 3.13 build to co-exist on your system with a traditional (GIL only) Python 3.13 build with minimal risk while installing or testing. This installation layout is itself experimental and is subject to change in future releases.

已知的注意事项和限制:

  • The UNIX command-line tools package, which is selected by default, will install links in /usr/local/bin for python3.13t, the free-threaded interpreter, and python3.13t-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 variables should be needed to use python3.13t.

  • For this release, the Shell profile updater package and the Update Shell Profile.command in /Applications/Python 3.13/ do not support the free-threaded package.

  • The free-threaded build and the traditional build have separate search paths and separate site-packages directories so, by default, if you need a package available in both builds, it may need to be installed in both. The free-threaded package will install a separate instance of pip for use with python3.13t.

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

      python3.13t -m pip install <package_name>

  • When working with multiple Python environments, it is usually safest and easiest to create and use virtual environments. This can avoid possible command name conflicts and confusion about which Python is in use:

    python3.13t -m venv <venv_name>

    然后执行 activate

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

    python3.13t -m idlelib

  • The interpreters in both builds respond to the same PYTHON environment variables which may have unexpected results, for example, if you have PYTHONPATH set in a shell profile. If necessary, there are command line options like -E to ignore these environment variables.

  • The free-threaded build links to the third-party shared libraries, such as OpenSSL and Tk, installed in the traditional framework. This means that both builds also share one set of trust certificates as installed by the Install Certificates.command script, thus it only needs to be run once.

  • If you cannot depend on the link in /usr/local/bin pointing to the python.org free-threaded python3.13t (for example, if you want to install your own version there or some other distribution does), you can explicitly set your shell PATH environment variable to include the PythonT framework bin directory:

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

    The traditional framework installation by default does something similar, except for Python.framework. Be aware that having both framework bin directories in PATH can lead to confusion if there are duplicate names like python3.13 in both; which one is actually used depends on the order they appear in PATH. The which python3.x or which python3.xt commands can show which path is being used. Using virtual environments can help avoid such ambiguities. Another option might be to create a shell alias to the desired interpreter, like:

    alias py3.13="/Library/Frameworks/Python.framework/Versions/3.13/bin/python3.13"
    alias py3.13t="/Library/Frameworks/PythonT.framework/Versions/3.13/bin/python3.13t"
    

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.13.0b2 release and selecting the free-threaded interpreter option:

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

# 下载安装器 pkg
curl -O https://www.python.org/ftp/python/3.13.0/${RELEASE}

# 创建安装器 choicechanges 文件来定制安装:
#    启用 PythonTFramework-3.13 包
#    并接受其他默认选项(安装所有其他包)
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>1</integer>
                <key>choiceAttribute</key>
                <string>selected</string>
                <key>choiceIdentifier</key>
                <string>org.python.Python.PythonTFramework-3.13</string>
        </dict>
</array>
</plist>
EOF

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

接下来你可以这样测试两个安装器构建版现在是否可用:

$ # 当 Unix Command Tools 包被启用时测试自由线程解释器是否已安装
$ /usr/local/bin/python3.13t -VV
Python 3.13.0b2 experimental free-threading build (v3.13.0b2:3a83b172af, Jun  5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]
$ # 并测试传统解释器
$ /usr/local/bin/python3.13 -VV
Python 3.13.0b2 (v3.13.0b2:3a83b172af, Jun  5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)]
$ # 当 /usr/local/bin 在 $PATH 中时测试它们在不带前缀的情况下是否可用
$ python3.13t -VV
Python 3.13.0b2 experimental free-threading build (v3.13.0b2:3a83b172af, Jun  5 2024, 12:57:31) [Clang 15.0.0 (clang-1500.3.9.4)]
$ python3.13 -VV
Python 3.13.0b2 (v3.13.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 用户和开发者的支持资源。