如何在 Amazon Linux 2 上编译和安装 Python 3.12+
发布: (2026年1月3日 GMT+8 10:41)
2 分钟阅读
原文: Dev.to
Source: Dev.to
介绍
Amazon Linux 2 默认仓库不提供 Python 3.12。
以下脚本:
- 手动构建 OpenSSL 1.1.1。
- 使用该 OpenSSL 编译 Python 3.12。
- 安装 Python 而不破坏系统自带的 Python。
- 安全地创建虚拟环境。
脚本概览 – 脚本的作用
系统更新和所需软件包
#!/bin/bash
# Update the system
sudo yum update -y
# Install development tools and required libraries
sudo yum groupinstall -y "Development Tools"
sudo yum install -y openssl-devel bzip2-devel libffi-devel zlib-devel \
readline-devel sqlite-devel ncurses-devel gdbm-devel \
db4-devel expat-devel gcc gcc-c++ make perl-core \
xz-devel libuuid-devel tk-devel tcl-devel
构建并安装 OpenSSL 1.1.1
cd /tmp/
wget https://www.openssl.org/source/openssl-1.1.1w.tar.gz
tar xzf openssl-1.1.1w.tar.gz
cd openssl-1.1.1w
./config --prefix=/usr/local/openssl --openssldir=/usr/local/openssl shared zlib
make -j "$(nproc)"
sudo make install
# Register the new library path
echo '/usr/local/openssl/lib' | sudo tee /etc/ld.so.conf.d/openssl.conf
sudo ldconfig
# Export environment variables for the current session
export PATH="/usr/local/openssl/bin:$PATH"
export LD_LIBRARY_PATH="/usr/local/openssl/lib:$LD_LIBRARY_PATH"
export PKG_CONFIG_PATH="/usr/local/openssl/lib/pkgconfig:$PKG_CONFIG_PATH"
export CPPFLAGS="-I/usr/local/openssl/include"
export LDFLAGS="-L/usr/local/openssl/lib"
# Verify installation
openssl version
下载、配置并编译 Python 3.12
cd /tmp/
wget https://www.python.org/ftp/python/3.12.0/Python-3.12.0.tgz
tar xzf Python-3.12.0.tgz
cd Python-3.12.0
# Configure the Python build.
# --enable-optimizations : improves performance (optional but recommended)
# --with-ensurepip=install : bundles pip
./configure --prefix=/usr/local --enable-optimizations --with-ensurepip=install
make -j "$(nproc)"
sudo make altinstall # installs as python3.12 without overwriting system python
验证安装
/usr/local/bin/python3.12 --version
/usr/local/bin/pip3.12 --version
创建虚拟环境
/usr/local/bin/python3.12 -m venv venv
source venv/bin/activate
(可选)创建便捷的符号链接
# Symlink for python3.12
sudo ln -s /usr/local/bin/python3.12 /usr/bin/python3.12
# Symlink for pip3.12
sudo ln -s /usr/local/bin/pip3.12 /usr/bin/pip3.12
# Verify the symlinks
python3.12 --version
pip3.12 --version