1. 检查系统是否已安装Python
默认情况下,Linux会自带安装Python,可以运行`python --version`命令查看。
2. 下载Python3安装包
可以通过`wget`命令下载,例如:
bash
wget
3. 解压安装包
使用`tar`命令解压,例如:
bash
tar -zxvf Python-3.6.5.tgz
4. 安装编译环境
不同的Linux发行版安装编译环境的命令有所不同,以CentOS为例:
bash
yum -y install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make gdbm-devel db4-devel libpcap-devel xz-devel libffi-devel
5. 编译安装
进入解压后的Python目录,执行以下命令:
bash
/configure --prefix=/usr/local/python3
make
make install
6. 创建软链接
为了方便使用,创建Python3和pip3的软链接:
bash
ln -s /usr/local/python3/bin/python3 /usr/bin/python3
ln -s /usr/local/python3/bin/pip3 /usr/bin/pip3
7. 配置环境变量
编辑`~/.bash_profile`文件,添加以下内容:
bash
配置python
export PYTHON_HOME=/usr/local/python3
export PATH=$PYTHON_HOME/bin:$PATH
保存退出后,执行`source ~/.bash_profile`使配置生效。
二、在Linux系统中安装Python3的常见问题及解决方案
1. 无法连接外网
如果在安装过程中遇到无法连接外网的情况,例如出现如下错误:
Loaded plugins: fastestmirror
00:00:00
Could not retrieve mirrorlist error was
14: curl6
One of the configured repositories failed (Unknown),
and yum doesn't have enough cached data to continue. At this point the only
safe thing yum can do is fail. There are a few ways to work "fix" this:
1. Contact the upstream for the repository and get them to fix the problem.
2. Reconfigure the baseurl/etc. for the repository, to point to a working
upstream. This is most often useful if you are using a newer
distribution release than is supported by the repository (and the
packages for the previous distribution release still work).
解决方案是编辑`/etc/sysconfig/network-scripts/ifcfg-ens33`文件(每个人的Linux中`ifcfg-ens33`名称不一定完全一样),配置网络连接。
2. 编译安装时出错
如果在编译安装过程中出现错误,例如执行`./configure --enable-optimizations`时出错,可能会导致`make && make install`时出现`Could not import runpy module`错误。解决方案是删除解压文件`Python-3.6.5.tgz`重新解压,然后执行`./configure --prefix=/root/training/Python-3.6.5`、`make`、`make install`。
3. 安装后无法找到Python3或pip3命令
如果安装后执行`python3`或`pip3`命令时提示`command not found`,可能是软链接未正确配置。可以通过`which python3 pip3`查找当前系统是否存在软链接,如果存在,需要删除这些软链接,然后重新创建并指定软链接,例如:
bash
sudo rm -rf /usr/bin/python3 /usr/bin/pip3
sudo ln -s /usr/local/bin/python3 /usr/bin/python3
sudo ln -s /usr/local/bin/pip3 /usr/bin/pip3
4. 安装SDK时提示“ModuleNotFoundError: No module named 'XX'”
此类问题是由于缺少某些必要的依赖库导致的,可以通过`pip install XX`解决该问题。
5. 安装SDK时提示“Command "python setup.py egg_info" failed with error code 1 in XX”
该问题通常是由Python版本或pip版本过低,或缺少必要的依赖项引起的。可以通过检查Python版本、更新pip版本、安装缺少的依赖库来解决。