为Windows编译Python安装包
Build Python binary installers for Windows.
本文探索了如何编译适用于 Windows 的 Python 二进制安装包。
前言
Python 官方对于 安全修复版本 (security fix release) 一般不提供 二进制安装包 (binary installer) 。
例如 Python 3.7.9
是 Python 3.7.x
系列中最后一个为 Windows 和 macOS 提供二进制安装包的版本, Python 3.7.10
及之后的 Python 3.7.x
系列版本则只提供 源代码 (source-only release) 。
那么如何在 Windows 上安装 当前 (2021-06-28) 最新的 Python 3.7.x
即 Python 3.7.11
呢?
文末 附下载。
准备工作
官方文档
查阅 官方文档 的 Python Setup and Usage 一节可以找到题为 Compiling Python on Windows 的说明:
If you want to compile CPython yourself, first thing you should do is get the source. You can download either the latest release’s source or just grab a fresh checkout.
The source tree contains a build solution and project files for Microsoft Visual Studio 2015, which is the compiler used to build the official Python releases. These files are in the PCbuild directory.
Check
PCbuild/readme.txt
for general information on the build process.
下载 Python 3.7.11
的 源代码 [1] [2] 并解压,找到 PCbuild/readme.txt
:
- Install Microsoft Visual Studio 2017 with Python workload and Python native development component.
- … requires an installation of Microsoft Visual Studio 2017 (MSVC 14.1) with the Python workload and its optional Python native development component selected. (For command-line builds, Visual Studio 2015 may also be used.)
- To build an installer package, refer to the README in the
Tools/msi
folder.
再找到 Tools/msi/README.txt
:
For testing, the installer should be built with the
Tools/msi/build.bat
script:build.bat [-x86] [-x64] [--doc]
For an official release, the installer should be built with the
Tools/msi/buildrelease.bat
script and environment variables:set PYTHON=<path to Python 2.7 or 3.4> set SPHINXBUILD=<path to sphinx-build.exe> set PATH=<path to Mercurial (hg.exe)>; <path to HTML Help Compiler (hhc.exe);%PATH% buildrelease.bat [-x86] [-x64] [-D] [-B] [-o <output directory>] [-c <certificate name>]
编译环境
本文在全新的 Windows_7_SP1_64-bit
虚拟机上进行编译;宿主机为 Windows_10_20H2_64-bit
;目标 Python 版本为 3.7.11
。
所需软件
Visual Studio 2017
虽然 文档 [3] 中说 VS2015 可能也行,但经过我的实际测试,VS2015 会在编译开始时的某一步报错,因此仍建议选择安装 VS2017 。
选择 Professional 或 Enterprise 等付费版本(30天试用期),可以在最后一步 “编译发行版” 时启用 PGO 优化 [4] 。
但经过实际测试,Community 版本也可以正常地启用 PGO 优化。
Visual Studio 2017 的安装包可以从 此处 下载,但需要注册并登录 Microsoft Azure DevOps 。当前有效的几个下载直链分别是:
- Visual Studio Community 2017 :
vs_Community.exe
- Visual Studio Professional 2017 :
vs_Professional.exe
- Visual Studio Enterprise 2017 :
vs_Enterprise.exe
该版本的详细信息为 Visual Studio 2017 (version 15.9.36) (MSVC 14.16)。
Python 3.6+
编译 Python 安装包需要先安装 Python 3.6 或之后的版本。本文采用 python-3.7.9-amd64.exe
。
简洁起见,我将 Python 的安装目录设置为 C:\Python\Python37
。你当然可以使用默认设置,但建议安装路径中不要含有空格等特殊字符。另外,记得勾选 Add Python 3.x to PATH
。
Git for Windows 2.x
Git 的版本并不关键,本文采用 Git-2.32.0-64-bit.exe
。
安装 VS2017
安装流程
双击运行 vs_Community.exe
等,即开始自动安装 Visual Studio Installer
。然后选择 工作负载 中的 “Python 开发 (Python development workload)” 及其可选子项 “Python 本机开发工具 (Python native development tools