指定目录编译安装Python3

编译安装Python3.10

CentOS中自带的Python版本是2,有其他原因需要在系统中安装Python3,但是最好不影响系统自带的版本。可以选用编译安装到指定目录方式实现

安装依赖包

yum install gcc patch libffi-devel python-devel zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel -y

下载安装包

# 利用国内淘宝的加速镜像下载源码包
wget https://npm.taobao.org/mirrors/python/3.10.1/Python-3.10.1.tgz

开始编译安装

tar zxf Python-3.10.1.tgz 
cd Python-3.10.1

# 预编译 并指定安装目录
./configure --prefix=/opt/python3 --enable-optimizations

# 编译安装
make && make install

添加到环境变量

ln -sf /opt/python3/bin/python3 /usr/local/bin/python3
ln -sf /opt/python3/bin/pip3 /usr/local/bin/pip3

问题修复

编译安装完成之后,出现import ssl报错

img

而且在使用pip安装软件包的时候,也有报错Can't connect to HTTTPS URL because the SSL moduleis not available

这是因为当前系统的OpenSSL太低,需要OpenSSL1.0.2及以上版本(但是这里我自己服务器环境为openssl-1.0.2g也不可以)

编译安装新版本OpenSSL

# 备份老版本的openssl
which openssl
/usr/bin/openssl
mv /usr/bin/openssl /usr/bin/openssl.old
rm -rf /etc/ssl/

# 安装新版本openssl
wget https://www.openssl.org/source/openssl-1.1.1l.tar.gz
tar -zxvf openssl-1.1.1l.tar.gz && cd openssl-1.1.1l
./config --prefix=/usr/local/openssl
make && make install
ln -s /usr/local/openssl/bin/openssl  /usr/local/bin/openssl
cp -r /usr/local/bin/openssl /usr/bin/
echo "/usr/local/openssl/lib" > /etc/ld.so.conf.d/openssl-1.1.1l.conf
ldconfig -v
openssl version -a

重新编译安装Python3

在运行./configure --prefix=/opt/python3后,修改Modules/Setup将SSL的目录改为新安装的OpenSSL目录

vim Modules/Setup

# Socket module helper for SSL support; you must comment out the other
# socket line above, and edit the OPENSSL variable:
_OPENSSL=/usr/local/openssl
_ssl _ssl.c \
    -I$(OPENSSL)/include -L$(OPENSSL)/lib \
    -lssl -lcrypto
_hashlib _hashopenssl.c \
     -I$(OPENSSL)/include -L$(OPENSSL)/lib \
     -lcrypto

# To statically link OpenSSL:
 _ssl _ssl.c \
     -I$(OPENSSL)/include -L$(OPENSSL)/lib \
     -l:libssl.a -Wl,--exclude-libs,libssl.a \
     -l:libcrypto.a -Wl,--exclude-libs,libcrypto.a
_hashlib _hashopenssl.c \
     -I$(OPENSSL)/include -L$(OPENSSL)/lib \
     -l:libcrypto.a -Wl,--exclude-libs,libcrypto.a

再运行make && make install

备份目录,可解压到其他服务器使用

当已经编译安装好的python版本打包,以便可以上传到其他服务器上使用

cd /opt
tar zcf python3.10.1.tgz python3

# 将python3.10.1.tgz上传到其他服务器上,解压后做软链就可以使用了
# 如果打包的时候,已经安装了第三方库,那么其他服务器上也可以直接使用安装好的库
posted @ 2022-01-05 17:13  KakuCicada  阅读(587)  评论(0编辑  收藏  举报