centos7编译安装Python312

1. 配置阿里云基础源

curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

image

2. 配置阿里云EPEL源

curl -o /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

image

3. 更新缓存

yum clean all && yum makecache

image

安装编译依赖

RUN yum install -y bzip2-devel libffi-devel zlib-devel make wget tar gzip

image

image

安装编译依赖openssl最新版本(后面编译安装Python的时候需要指定openssl路径)

安装指南:https://www.cnblogs.com/fqy6/articles/19302298

# 查看系统OpenSSL版本

openssl version

# 查找OpenSSL安装位置

which openssl
ldconfig -p | grep ssl

# 查看是否有多个版本

find /usr -name "libssl.so*" 2>/dev/null
find /usr/local -name "libssl.so*" 2>/dev/null

image

[root@82d239ec712c Python-3.12.0]# openssl version
OpenSSL 3.6.0 1 Oct 2025 (Library: OpenSSL 3.6.0 1 Oct 2025)
[root@82d239ec712c Python-3.12.0]# which openssl
bash: which: command not found
[root@82d239ec712c Python-3.12.0]# ldconfig -p | grep ssl
	libssl3.so (libc6,x86-64) => /lib64/libssl3.so
	libssl.so.10 (libc6,x86-64) => /lib64/libssl.so.10
	libssl.so.3 (libc6,x86-64) => /usr/local/ssl/lib64/libssl.so.3
	libssl.so (libc6,x86-64) => /usr/local/ssl/lib64/libssl.so
	libcrypto.so.3 (libc6,x86-64) => /usr/local/ssl/lib64/libcrypto.so.3
	libcrypto.so (libc6,x86-64) => /usr/local/ssl/lib64/libcrypto.so
[root@82d239ec712c Python-3.12.0]# find /usr -name "libssl.so*" 2>/dev/null
/usr/lib64/libssl.so.1.0.2k
/usr/lib64/libssl.so.10
/usr/local/src/openssl-3.6.0/libssl.so.3
/usr/local/src/openssl-3.6.0/libssl.so
/usr/local/ssl/lib64/libssl.so.3
/usr/local/ssl/lib64/libssl.so
[root@82d239ec712c Python-3.12.0]# find /usr/local -name "libssl.so*" 2>/dev/null
/usr/local/src/openssl-3.6.0/libssl.so.3
/usr/local/src/openssl-3.6.0/libssl.so
/usr/local/ssl/lib64/libssl.so.3
/usr/local/ssl/lib64/libssl.so
[root@82d239ec712c Python-3.12.0]# 

下载并编译安装 Python 3.12

cd /opt
wget https://www.python.org/ftp/python/3.12.0/Python-3.12.0.tgz
tar -xzf Python-3.12.0.tgz
# 清理之前的编译
# 完全清理
cd /opt/Python-3.12.0
make distclean 2>/dev/null || make clean 2>/dev/null

# 删除所有可能的残留文件
find . -name "*.pyc" -delete
find . -name "__pycache__" -type d -exec rm -rf {} +
rm -rf build/ Modules/Setup.local config.cache config.status

# 方法1:指定新OpenSSL的安装路径
# 移除 --enable-optimizations 以加速编译,添加 --prefix 指定安装路径
./configure \
  --prefix=/usr/local/python312 \
  --with-openssl=/usr/local/ssl \
  LDFLAGS="-L/usr/local/ssl/lib64" \
  CPPFLAGS="-I/usr/local/ssl/include"

# 编译(使用多核编译提高速度)
make -j$(nproc)

# 如果不知道核心数,可以使用
make -j$(nproc 2>/dev/null || echo 4)

# 安装
make install

# 使用altinstall避免替换系统Python
sudo make altinstall

# 或者安装到指定位置
make install DESTDIR=/opt/python312

编译完成

if test $? -ne 0 ; then \
	echo "generate-posix-vars failed" ; \
	rm -f ./pybuilddir.txt ; \
	exit 1 ; \
fi
./python -E -c 'import sys ; from sysconfig import get_platform ; print("%s-%d.%d" % (get_platform(), *sys.version_info[:2]))' >platform
The following modules are *disabled* in configure script:
_sqlite3                                                       

The necessary bits to build these optional modules were not found:
_curses               _curses_panel         _lzma              
_tkinter              _uuid                 readline           
To find the necessary bits, look in configure.ac and config.log.

Checked 111 modules (31 built-in, 72 shared, 1 n/a on linux-x86_64, 1 disabled, 6 missing, 0 failed on import)
[root@82d239ec712c Python-3.12.0]#

配置成功完成了!虽然显示一些模块被禁用或缺失,但这是正常的,特别是对于最小化安装。现在可以继续编译和安装了。

make install

fi
if test "x" != "x" ; then \
	rm -f /usr/local/python312/bin/python3-intel64; \
	(cd /usr/local/python312/bin; ln -s python3.12-intel64 python3-intel64) \
fi
rm -f /usr/local/python312/share/man/man1/python3.1
(cd /usr/local/python312/share/man/man1; ln -s python3.12.1 python3.1)
if test "xupgrade" != "xno"  ; then \
	case upgrade in \
		upgrade) ensurepip="--upgrade" ;; \
		install|*) ensurepip="" ;; \
	esac; \
	 ./python -E -m ensurepip \
		$ensurepip --root=/ ; \
fi
Looking in links: /tmp/tmpaa10y7ru
Processing /tmp/tmpaa10y7ru/pip-23.2.1-py3-none-any.whl
Installing collected packages: pip
  WARNING: The scripts pip3 and pip3.12 are installed in '/usr/local/python312/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed pip-23.2.1
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
[root@82d239ec712c Python-3.12.0]#

Python 3.12已经成功安装了。现在需要设置环境变量和进行一些配置。

1. 将Python添加到PATH

# 临时添加到PATH(当前会话有效)
export PATH=/usr/local/python312/bin:$PATH

# 永久添加到PATH
echo 'export PATH=/usr/local/python312/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

2. 验证安装

# 检查Python版本
python3.12 --version
python3 --version 2>/dev/null || echo "python3链接不存在"

# 检查pip版本
pip3.12 --version

# 测试SSL模块
python3.12 -c "import ssl; print(f'OpenSSL版本: {ssl.OPENSSL_VERSION}')"

3. 创建符号链接

# 创建python3链接
sudo ln -sf /usr/local/python312/bin/python3.12 /usr/local/bin/python3
sudo ln -sf /usr/local/python312/bin/python3.12 /usr/bin/python3  # 如果需要系统级访问

# 创建pip3链接
sudo ln -sf /usr/local/python312/bin/pip3.12 /usr/local/bin/pip3
sudo ln -sf /usr/local/python312/bin/pip3.12 /usr/bin/pip3

# 验证链接
ls -la /usr/local/bin/python* /usr/local/bin/pip*

image

4. 修复pip警告

# 创建pip配置文件
mkdir -p ~/.config/pip
cat > ~/.config/pip/pip.conf << EOF
[global]
break-system-packages = true
EOF

# 或者全局配置
sudo mkdir -p /etc/pip
sudo tee /etc/pip.conf << EOF
[global]
break-system-packages = true
EOF

5. 测试完整功能

cat > test_installation.py << 'EOF'
#!/usr/bin/env python3.12
import sys
import ssl
import json
import urllib.request

print("=== Python 3.12 完整安装测试 ===")
print(f"Python版本: {sys.version}")
print(f"安装路径: {sys.prefix}")
print(f"执行路径: {sys.executable}")

print("\n=== SSL/TLS 测试 ===")
print(f"OpenSSL版本: {ssl.OPENSSL_VERSION}")
print(f"支持TLS 1.3: {ssl.HAS_TLSv1_3}")

# 测试HTTPS
try:
    ctx = ssl.create_default_context()
    req = urllib.request.Request('https://httpbin.org/json', 
                                 headers={'User-Agent': 'Python-3.12-Test'})
    with urllib.request.urlopen(req, timeout=10, context=ctx) as response:
        data = json.load(response)
        print("HTTPS连接测试: ✓ 成功")
except Exception as e:
    print(f"HTTPS连接测试: ✗ 失败 - {e}")

print("\n=== 包管理测试 ===")
import subprocess
result = subprocess.run([sys.executable, '-m', 'pip', 'list'], 
                       capture_output=True, text=True)
print(f"已安装包数量: {len(result.stdout.splitlines()) - 2}")

print("\n=== 虚拟环境测试 ===")
import venv
import tempfile
import os

with tempfile.TemporaryDirectory() as tmpdir:
    venv.create(tmpdir, with_pip=True)
    print(f"虚拟环境创建: ✓ 成功 ({tmpdir})")

print("\n=== 安装测试完成 ===")
EOF

python3.12 test_installation.py

6. 安装常用工具包

# 升级pip
pip3.12 install --upgrade pip setuptools wheel

# 安装常用开发工具
pip3.12 install \
    virtualenv \
    ipython \
    black \
    flake8 \
    pytest \
    requests \
    numpy \
    pandas

# 验证安装
pip3.12 list | head -20

image

7. 配置开发环境

# 创建项目目录
mkdir -p ~/projects/python312
cd ~/projects/python312

# 创建虚拟环境
python3.12 -m venv venv
source venv/bin/activate

# 在虚拟环境中测试
python -c "import sys; print(f'虚拟环境Python: {sys.executable}')"
deactivate

8. 设置Jupyter支持(可选)

# 安装Jupyter
pip3.12 install jupyter notebook

# 生成Jupyter配置
jupyter notebook --generate-config

# 创建启动脚本
cat > ~/start_jupyter.sh << 'EOF'
#!/bin/bash
source /usr/local/python312/bin/activate 2>/dev/null || true
jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root
EOF

chmod +x ~/start_jupyter.sh

9. 创建服务脚本

# 创建Python环境加载脚本
sudo tee /etc/profile.d/python312.sh << 'EOF'
export PATH=/usr/local/python312/bin:$PATH
export PYTHONPATH=/usr/local/python312/lib/python3.12/site-packages:$PYTHONPATH
alias python3='/usr/local/python312/bin/python3.12'
alias pip3='/usr/local/python312/bin/pip3.12'
EOF

source /etc/profile.d/python312.sh

10. 验证系统集成

# 测试Python可用性
which python3.12
which python3
which pip3.12
which pip3

# 测试导入关键模块
python3.12 -c "
import sys
print('sys模块:', sys.version)
import ssl
print('ssl模块:', ssl.OPENSSL_VERSION)
import sqlite3
print('sqlite3版本:', sqlite3.sqlite_version)
import hashlib
print('hashlib可用:', hashlib.algorithms_available)
"

# 检查Python配置
python3.12 -m sysconfig

11. 清理编译文件

# 清理Python源码目录
cd /opt/Python-3.12.0
make clean

# 删除不需要的文件
rm -rf __pycache__/ build/

# 或者完全删除源码(如果需要空间)
# cd /opt && rm -rf Python-3.12.0

12. 故障排除

如果遇到权限问题:

# 修复pip权限
python3.12 -m pip install --upgrade pip --user

# 或者使用虚拟环境
python3.12 -m venv ~/py312
source ~/py312/bin/activate
pip install --upgrade pip

如果遇到模块导入问题:

# 检查Python路径
python3.12 -c "import sys; print('\n'.join(sys.path))"

# 检查动态库
ldd /usr/local/python312/bin/python3.12

# 添加库路径
echo '/usr/local/python312/lib' | sudo tee /etc/ld.so.conf.d/python312.conf
sudo ldconfig

13. 快速验证脚本

cat > ~/check_python312.sh << 'EOF'
#!/bin/bash
echo "=== Python 3.12 环境检查 ==="
echo "1. 版本信息:"
python3.12 --version 2>/dev/null || echo "Python 3.12 未找到"
python3 --version 2>/dev/null || echo "python3 链接不存在"

echo -e "\n2. 路径检查:"
which python3.12 2>/dev/null || echo "python3.12 不在PATH中"
which python3 2>/dev/null || echo "python3 不在PATH中"

echo -e "\n3. 模块测试:"
python3.12 -c "
modules = ['ssl', 'json', 'os', 'sys', 'hashlib', 'sqlite3', 'venv']
for mod in modules:
    try:
        __import__(mod)
        print(f'  ✓ {mod}')
    except:
        print(f'  ✗ {mod}')
"

echo -e "\n4. PIP测试:"
pip3.12 --version 2>/dev/null || echo "pip3.12 未找到"

echo -e "\n=== 检查完成 ==="
EOF

chmod +x ~/check_python312.sh
./check_python312.sh

现在Python 3.12已经成功安装!你可以使用 python3.12python3(如果创建了链接)来运行Python,使用 pip3.12pip3 来管理包。

posted @ 2025-12-03 15:41  Haloiwuhan  阅读(56)  评论(0)    收藏  举报