一、
在 CentOS 中安装 Python 3 可以通过几种方法实现,具体取决于你的 CentOS 版本。以下是最常用的方法:
方法 1: 使用 yum
安装(CentOS 7 及以上)
在 CentOS 7 及以上版本中,可以通过 yum
包管理器直接安装 Python 3。
步骤:
-
更新包管理器:
sudo yum -y update
-
安装 Python 3:
CentOS 7 默认使用 Python 2.7,你可以安装 Python 3 并保留 Python 2。sudo yum -y install python3
-
验证安装:
安装完成后,你可以通过以下命令验证是否安装成功:python3 --version
如果显示 Python 3.x.x 版本号,说明安装成功。
-
安装 pip(Python 包管理器):
通常,pip
会随 Python 3 一起安装,但你也可以手动安装或升级:sudo yum install python3-pip
验证
pip
是否安装成功:pip3 --version
方法 2: 使用 Software Collections (SCL) 安装(适用于 CentOS 7)
Software Collections (SCL) 是一种允许在 CentOS 中安装和使用多个软件版本的工具,包括 Python 3。
步骤:
-
安装 SCL:
sudo yum -y install centos-release-scl
-
安装 Python 3:
使用 SCL 安装 Python 3.6(或其他版本):sudo yum -y install rh-python36
-
启用 Python 3:
安装完成后,启用 Python 3 环境:scl enable rh-python36 bash
-
验证安装:
python3 --version
方法 3: 从源代码编译安装(适用于高级用户)
如果你需要特定版本的 Python 3,或者在 CentOS 6 中无法通过 yum
安装 Python 3,你可以选择从源代码编译安装。
步骤:
-
安装依赖包:
首先,安装构建 Python 所需的依赖包:sudo yum -y groupinstall "Development Tools" sudo yum -y install wget openssl-devel bzip2-devel libffi-devel
-
下载 Python 源代码:
选择你需要的 Python 版本,下载源代码。例如,下载 Python 3.9.1:cd /usr/src sudo wget https://www.python.org/ftp/python/3.9.1/Python-3.9.1.tgz
-
解压源代码:
sudo tar xzf Python-3.9.1.tgz cd Python-3.9.1
-
编译 Python:
配置和编译 Python:sudo ./configure --enable-optimizations sudo make altinstall
注意:使用
altinstall
而不是install
,以避免覆盖系统的默认 Python 版本。 -
验证安装:
编译完成后,验证安装: