5.於 macOS 使用 Python

This document aims to give an overview of macOS-specific behavior you shouldknow about to get started with Python on Mac computers.Python on a Mac running macOS is very similar to Python on other Unix-derived platforms,but there are some differences in installation and some features.

There are various ways to obtain and install Python for macOS.Pre-built versions of the most recent versions of Python are availablefrom a number of distributors. Much of this document describes use ofthe Pythons provided by the CPython release team for download fromthepython.org website. SeeAlternative Distributions for some other options.

5.1.Using Python for macOS frompython.org

5.1.1.安裝步驟

Forcurrent Python versions(other than those insecurity status), the release team produces aPython for macOS installer package for each new release.A list of available installersis availablehere.We recommend using the most recent supported Python version where possible.Current installers provide auniversal2 binary buildof Python which runs natively on all Macs (Apple Silicon and Intel) that aresupported by a wide range of macOS versions,currently typically from at leastmacOS 10.13 High Sierra on.

The downloaded file is a standard macOS installer package file (.pkg).File integrity information (checksum, size, sigstore signature, etc) for each file is includedon the release download page. Installer packages and their contents are signed and notarizedwithPythonSoftwareFoundation Apple Developer ID certificatesto meetmacOS 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 severalinstaller windows steps.

../_images/mac_installer_01_introduction.png

Clicking on theContinue button brings up theRead Me for this installer.Besides other important information, theRead Me documents which Python version isgoing to be installed and on what versions of macOS it is supported. You may needto scroll through to read the whole file. By default, thisRead Me will also beinstalled in/Applications/Python3.13/ and available to read anytime.

../_images/mac_installer_02_readme.png

Clicking onContinue proceeds to display the license for Python and forother included software. You will then need toAgree to the license termsbefore proceeding to the next step. This license file will also be installedand available to be read later.

../_images/mac_installer_03_license.png

After the license terms are accepted, the next step is theInstallation Typedisplay. For most uses, the standard set of installation operations is appropriate.

../_images/mac_installer_04_installation_type.png

By pressing theCustomize button, you can choose to omit or select certain packagecomponents of the installer. Click on each package name to see a description ofwhat it installs.To also install support for the optional experimental free-threaded feature,seeInstalling Free-threaded Binaries.

../_images/mac_installer_05_custom_install.png

In either case, clickingInstall will begin the install process by askingpermission to install new software. A macOS user name withAdministrator privilegeis needed as the installed Python will be available to all users of the Mac.

When the installation is complete, theSummary window will appear.

../_images/mac_installer_06_summary.png

Double-click on theInstall Certificates.commandicon or file in the/Applications/Python3.13/ window to complete theinstallation.

../_images/mac_installer_07_applications.png

This will open a temporaryTerminal shell window thatwill use the new Python to download and install SSL root certificatesfor its use.

../_images/mac_installer_08_install_certificates.png

IfSuccessfullyinstalledcertifi andupdatecomplete appearsin the terminal window, the installation is complete.Close this terminal window and the installer window.

預設安裝會包含:

  • 會有一個Python3.13 資料夾在你的Applications 資料夾中。在這裡你可以找到IDLE,它是作為官方 Python 發行版標準組成的開發環境;以及Python Launcher,它負責處理在Finder 中雙擊 Python 腳本的操作。

  • /Library/Frameworks/Python.framework 框架,包括 Python 可執行檔案 (executable) 和函式庫 (library)。安裝程式將此位置新增到 shell 路徑。要解除安裝 Python ,你可以移除這三個東西。Python 可執行檔案的符號連結 (symlink) 則放在/usr/local/bin/ 中。

備註

Recent versions of macOS include apython3 command in/usr/bin/python3that links to a usually older and incomplete version of Python provided by and for use bythe Apple development tools,Xcode or theCommand Line Tools for Xcode.You should never modify or attempt to delete this installation, as it isApple-controlled and is used by Apple-provided or third-party software. Ifyou choose to install a newer Python version frompython.org, you will havetwo different but functional Python installations on your computer thatcan co-exist. The default installer options should ensure that itspython3will be used instead of the systempython3.

5.1.2.如何執行 Python 腳本

There are two ways to invoke the Python interpreter.If you are familiar with using a Unix shell in a terminalwindow, you can invokepython3.13 orpython3 optionallyfollowed by one or more command line options (described in命令列與環境).The Python tutorial also has a useful section onusing Python interactively from a shell.

You can also invoke the interpreter through an integrateddevelopment environment.IDLE --- Python 編輯器與 shell is a basic editor and interpreter environmentwhich is included with the standard distribution of Python.IDLE includes a Help menu that allows you to access Python documentation. If youare completely new to Python, you can read the tutorial introductionin that document.

There are many other editors and IDEs available, see編輯器與 IDEfor more information.

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

python3.13myscript.py

從 Finder 執行你的腳本時,你可以:

  • 把它拖曳到Python Launcher

  • 透過 Finder Info 視窗選擇Python Launcher 作為開啟腳本(或任何.py 腳本)的預設應用程式,然後雙擊腳本。Python Launcher 有各種用來控制腳本啟動方式的選項。拖曳選項可以讓你一次更改多個選項,或使用其Preferences 選單以全域性地更改內容。

Be aware that running the script directly from the macOS Finder mightproduce different results than when running from a terminal window asthe script will not be run in the usual shell environment includingany 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.Alternative Distributions

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

ActivePython

Installer with multi-platform compatibility, documentation

Anaconda

Popular scientific modules (such as numpy, scipy, and pandas) and theconda package manager.

Homebrew

Package manager for macOS including multiple versions of Python and manythird-party Python-based packages (including numpy, scipy, and pandas).

MacPorts

Another package manager for macOS including multiple versions of Python and manythird-party Python-based packages. May include pre-built versions of Python andmany packages for older versions of macOS.

Note that distributions might not include the latest versions of Python orother libraries, and are not maintained or supported by the core Python team.

5.3.安裝額外的 Python 套件

更多資訊請見Python Packaging User Guide

5.4.開發 GUI 程式

於 Mac 上使用 Python 來建立 GUI 應用程式有許多選項。

標準的 Python GUI 工具套件是基於跨平臺 Tk 工具套件 (https://www.tcl.tk) 的tkinter。macOS 原生版本的 Tk 有包含於安裝程式中。

PyObjC 是一個 Apple Objective-C/Cocoa 框架的 Python 繫結 (binding)。有關 PyObjC 的資訊請見pyobjc

有許多替代 macOS GUI 工具套件可用,包含:

  • PySideQt GUI 工具包的官方 Python 繫結。

  • PyQt:Qt 的替代 Python 繫結。

  • Kivy:一個支援桌面和行動平臺的跨平臺 GUI 工具包。

  • TogaBeeWare 專案的一部分;支援桌面、行動、網頁和控制台應用程式。

  • wxPython:一個支援桌面作業系統的跨平臺工具包。

5.5.進階主題

5.5.1.Installing Free-threaded Binaries

在 3.13 版被加入:(實驗性的)

備註

Everything described in this section is considered experimental,and should be expected to change in future releases.

Thepython.orgPython for macOSinstaller package can optionally install an additional build ofPython 3.13 that supportsPEP 703, the experimental free-threading feature(running with theglobal interpreter lock disabled).Check the release page onpython.org for possible updated information.

Because this feature is still considered experimental, the support for itis not installed by default. It is packaged as a separate install option,available by clicking theCustomize button on theInstallation Typestep of the installer as described above.

../_images/mac_installer_09_custom_install_free_threaded.png

If the box next to theFree-threaded Python package name is checked,a separatePythonT.framework will also be installedalongside the normalPython.framework in/Library/Frameworks.This configuration allows a free-threaded Python 3.13 build to co-existon your system with a traditional (GIL only) Python 3.13 build withminimal risk while installing or testing. This installation layout is itselfexperimental and is subject to change in future releases.

Known cautions and limitations:

  • TheUNIX command-line tools package, which is selected by default,will install links in/usr/local/bin forpython3.13t,the free-threaded interpreter, andpython3.13t-config,a configuration utility which may be useful for package builders.Since/usr/local/bin is typically included in your shellPATH,in most cases no changes to yourPATH environment variables shouldbe needed to usepython3.13t.

  • For this release, theShell profile updater package and theUpdateShellProfile.command in/Applications/Python3.13/do not support the free-threaded package.

  • The free-threaded build and the traditional build have separate searchpaths and separatesite-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 ofpip for usewithpython3.13t.

    • To install a package usingpip without avenv:

      python3.13t-mpipinstall<package_name>

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

    python3.13t-mvenv<venv_name>

    然後activate

  • 執行 free-threaded(自由執行緒)版本的 IDLE:

    python3.13t-midlelib

  • The interpreters in both builds respond to the samePYTHON environment variableswhich may have unexpected results, for example, if you havePYTHONPATHset in a shell profile. If necessary, there arecommand line options like-Eto ignore these environment variables.

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

  • If you cannot depend on the link in/usr/local/bin pointing to thepython.org free-threadedpython3.13t (for example, if you wantto install your own version there or some other distribution does),you can explicitly set your shellPATH environment variable toinclude thePythonT frameworkbin directory:

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

    The traditional framework installation by default does something similar,except forPython.framework. Be aware that having both frameworkbindirectories inPATH can lead to confusion if there are duplicate nameslikepython3.13 in both; which one is actually used depends on the orderthey appear inPATH. Thewhichpython3.x orwhichpython3.xtcommands can show which path is being used. Using virtual environmentscan help avoid such ambiguities. Another option might be to createa shellalias to the desired interpreter, like:

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

5.5.2.使用命令列安裝

If you want to use automation to install thepython.org installer package(rather than by using the familiar macOSInstaller GUI app),the macOS command lineinstaller utility lets you select non-defaultoptions, too. If you are not familiar withinstaller, it can besomewhat cryptic (seeman installer for more information).As an example, the following shell snippet shows one way to do it,using the3.13.0b2 release and selecting the free-threaded interpreteroption:

RELEASE="python-3.13.0b2-macos11.pkg"# download installer pkgcurl-Ohttps://www.python.org/ftp/python/3.13.0/${RELEASE}# create installer choicechanges to customize the install:#    enable the PythonTFramework-3.13 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>1</integer>                <key>choiceAttribute</key>                <string>selected</string>                <key>choiceIdentifier</key>                <string>org.python.Python.PythonTFramework-3.13</string>        </dict></array></plist>EOFsudoinstaller-pkg./${RELEASE}-applyChoiceChangesXML./choicechanges.plist-target/

You can then test that both installer builds are now available with something like:

$# test that the free-threaded interpreter was installed if the Unix Command Tools package was enabled$/usr/local/bin/python3.13t-VVPython 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)]$#    and the traditional interpreter$/usr/local/bin/python3.13-VVPython 3.13.0b2 (v3.13.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.13t-VVPython 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-VVPython 3.13.0b2 (v3.13.0b2:3a83b172af, Jun  5 2024, 12:50:24) [Clang 15.0.0 (clang-1500.3.9.4)]

備註

Currentpython.org installers only install to fixed locations like/Library/Frameworks/,/Applications, and/usr/local/bin.You cannot use theinstaller-domain option to install toother locations.

5.5.3.發行 Python 應用程式

A range of tools exist for converting your Python code into a standalonedistributable application:

  • py2app:支援從 Python 專案打包成 macOS.app

  • BriefcaseBeeWare 專案的一部分;支援建立 macOS.app 的跨平台打包工具,亦為管理簽署和驗證 (notarization) 的工具。

  • PyInstaller:一個跨平臺打包工具,可以將單一檔案或資料夾打包成可分發的檔案。

5.5.4.App Store Compliance

Apps submitted for distribution through the macOS App Store must pass Apple'sapp review process. This process includes a set of automated validation rulesthat inspect the submitted application bundle for problematic code.

The Python standard library contains some code that is known to violate theseautomated rules. While these violations appear to be false positives, Apple'sreview rules cannot be challenged. Therefore, it is necessary to modify thePython standard library for an app to pass App Store review.

The Python source tree containsa patch file that will removeall code that is known to cause issues with the App Store review process. Thispatch is applied automatically when CPython is configured with the--with-app-store-compliance option.

This patch is not normally required to use CPython on a Mac; nor is it requiredif you are distributing an appoutside the macOS App Store. It isonlyrequired if you are using the macOS App Store as a distribution channel.

5.6.其他資源

Thepython.org Help page has links to many useful resources.ThePythonmac-SIG mailing listis another support resource specifically for Python users and developers on the Mac.