Python3.7源码编译
阅读原文时间:2023年08月24日阅读:1

1.下载Python3.7.0源码

git clone https://github.com/python/cpython.gitgit checkout v3.7.0

wget https://www.python.org/ftp/python/3.7.0/Python-3.7.0.tar.xz

源码目录结构如下所示:


(1)Include目录:包含Python提供的所有头文件,如果用户需要自己用C或C++来编写自定义模块扩展Python,那么就需要用到这里提供的头文件。

(2)Lib目录:包含了Python自带的所有标准库,且都是用Python语言编写的。

(3)Modules目录:包含了所有用C语言编写的模块,比如math、hashlib等。它们都是那些对速度要求非常严格的模块。而相比而言,Lib目录下则是存放一些对速度没有太严格要求的模块,比如os。

(4)Parser目录:包含了Python解释器中的Scanner和Parser部分,即对Python源代码进行词法分析和语法分析的部分。除此以外,此目录还包含了一些有用的工具,这些工具能够根据Python语言的语法自动生成Python语言的词法和语法分析器,与YACC(Yet Another Compiler Compiler)非常类似。

(5)Objects目录:包含了所有Python的内建对象,包括整数、list、dict等。同时,该目录还包括了Python在运行时需要的所有的内部使用对象的实现。

(6)Python目录:包含了Python解释器中的Compiler和执行引擎部分,是Python运行的核心所在。

(7)PCbuild目录:包含了Visual Studio 2003的工程文件,研究Python源代码就从这里开始。

(8)Programs目录:包含了Python二进制可执行文件的源码。

2.编译和安装Python3.7.0源码

libffi是Python中用来支持C扩展的库:

sudo apt install -y zlib1g zlib1g-dev libffi-dev openssl libssl-dev

./configure --prefix=/home/rasa/Downloads/PythonSorceCode/Python3.7_compilemakemake install

make命令后报错如下所示:

因为openssl 1.0.1存在安全问题,所以Python3.7以上建议使用libressl代替openssl,故需通过源码编译安装libressl,如下所示:

# 下载和编译libresslwget https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-3.0.2.tar.gztar -zxvf libressl-3.0.2.tar.gzsudo mkdir /usr/local/libresslcd libressl-3.0.2./configure --prefix=/usr/local/libressl && make && sudo make # 创建软连接代替opensslsudo mv /usr/bin/openssl /usr/bin/openssl.baksudo mv /usr/include/openssl /usr/include/openssl.baksudo ln -s /usr/local/libressl/bin/openssl /usr/bin/opensslsudo ln -s /usr/local/libressl/include/openssl /usr/include/opensslecho /usr/local/libressl/lib >> /etc/ld.so.conf.d/libressl-3.0.2.confsudo ldconfig -v# 验证是否安装完成openssl versionexport LDFLAGS="-L/usr/local/libressl/lib"export CPPFLAGS="-I/usr/local/libressl/include"export PKG_CONFIG_PATH="/usr/local/libressl/lib/pkgconfig"

再次执行命令编译Python3.7.0源码:

./configure --prefix=/home/rasa/Downloads/PythonSorceCode/Python3.7_compilemakesudo make install


参考文献:

[1]Python源代码的组织:https://flaggo.github.io/python3-source-code-analysis/preface/code-organization/

[2]Python requires an OpenSSL 1.0.2 or 1.1 compatible libssl with X509_VERIFY_P:https://www.cnblogs.com/apexchu/p/16294733.html