背景:Ubuntu20.04 LTS,系统自带python3.8 python2.7,默认为python3.8
需求:装了一个python3.9,想将3.9设为默认,且终端输入python或python3都指向默认3.9
进入终端,输入以下查看当前python各版本的情况
python # 3.8为default
ll /usr/bin/ |grep python
发现:
有python3.8*、 python2.7*、python3.9*三个版本及三条软链接,终端输入python或python3都指向默认3.8;
python -> python3.8*
python3 -> python3.8*
python2 -> python2.7*
解决尝试(不推荐):
强制添加新的软链接,并覆盖掉原来的python、python3软链接
sudo ln -sf /usr/bin/python3.9 /usr/bin/python
sudo ln -sf /usr/bin/python3.9 /usr/bin/python3
重新查看当前python各版本的情况
python # 3.9为default
ll /usr/bin/ |grep python #python、python3软链接已成功更改为指向python3.9
pip --version
pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.8)
但是pip命令仍然会将所有内容安装到Python3.8目录中,卸载pip再重装也一样,只好用下面的解决办法
推荐办法:
使用 update-alternatives 来为整个系统更改Python 版本
查看python替代版本信息
sudo update-alternatives --display python
但是结果为update-alternatives: error: no alternatives for python
python的替代版本尚未被update-alternatives
更新一下python的替代列表
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
# update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.8 2
# update-alternatives: using /usr/bin/python3.8 to provide /usr/bin/python (python) in auto mode
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.9 3
# update-alternatives: using /usr/bin/python3.9 to provide /usr/bin/python (python) in auto mode
查看或配置更新的替代列表,python3.9的优先级为3,最高,这样就修改了默认为3.9
sudo update-alternatives --config python
python3的指向更改同python的一样:
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.8 1
# update-alternatives: using /usr/bin/python3.8 to provide /usr/bin/python (python) in auto mode
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.9 2
# update-alternatives: using /usr/bin/python3.9 to provide /usr/bin/python (python) in auto mode
查看当前python各版本的情况
python # 3.9为default
ll /usr/bin/ |grep python #python软链接已成功更改为指向python3.9
以上操作确认没问题后建议卸载重装pip
sudo apt purge python3-pip
sudo apt autoremove
sudo apt install python3-pip
再查看pip的信息,
pip --version
# pip 20.0.2 from /usr/lib/python3/dist-packages/pip (python 3.9),出现这个即改成功了,出错则可参考下面的错误案例
错误案例
ModuleNotFoundError: No module named 'apt_pkg’问题的解决方法
cd /usr/lib/python3/dist-packages/
sudo ln -s apt_pkg.cpython-38m-x86_64-linux-gnu.so apt_pkg.so
如果报apt_pkg.so已存在,则使用命令强制建立软链接
sudo ln -fs apt_pkg.cpython-38m-x86_64-linux-gnu.so apt_pkg.so
ModuleNotFoundError: No module named 'distutils.util’问题的解决方法
卸载重装python3-distutils
sudo apt purge python3-distutils
sudo apt autoremove
sudo apt install python3-distutils