ubuntu desktop 22.04 安装多版本Python

二进制安装

添加存储库

sudo add-apt-repository ppa:deadsnakes/ppa
sudo apt-get update

安装python

sudo apt-get install python3.11

安装多个版本python

sudo apt-get install python3.11 python3.9 python3.8

将旧版本的 Python 和新版本添加到更新替代方案

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.11 2

键入以下命令以配置 python3, 输入需要选择python

sudo update-alternatives --config python3

有 2 个候选项可用于替换 python3 (提供 /usr/bin/python3)。

  选择       路径               优先级  状态
------------------------------------------------------------
  0            /usr/bin/python3.11   2         自动模式
  1            /usr/bin/python3.10   1         手动模式
* 2            /usr/bin/python3.11   2         手动模式

要维持当前值[*]请按<回车键>,或者键入选择的编号:^^^^^^

查看版本 python3 -V

编译安装

默认安装到/usr/local/bin

sudo apt install gcc dialog libaugeas0 augeas-lenses libssl-dev libffi-dev ca-certificates
tar xzf Python-3.11.3.tgz
pushd Python-3.11.3 > /dev/null
./configure --enable-optimizations
 make -j 8 && make altinstall

配置默认python3

sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.10 1
sudo update-alternatives --install /usr/bin/python3 python3 /usr/local/bin/python3.11 2
sudo update-alternatives --config python3

集成环境

conda 占用空间太大,每个环境都要重复安装基础组件,适合AI项目

pyenv

存在的问题

apt update 报错

Traceback (most recent call last):
  File "/usr/lib/cnf-update-db", line 3, in <module>
    import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'
E: Problem executing scripts APT::Update::Post-Invoke-Success 'if /usr/bin/test -w /var/lib/command-not-found/ -a -e /usr/lib/cnf-update-db; then /usr/lib/cnf-update-db > /dev/null; fi'
$ cd /usr/lib/python3/dist-packages
$ ls -la | grep "apt_pkg.cpython"
$ sudo cp apt_pkg.cpython-310-x86_64-linux-gnu.so apt_pkg.so

编译安装的python使用此方法无法解决

gnome-terminal等基于的python软件无法使用

cd /usr/lib/python3/dist-packages/gi/

sudo cp _gi_cairo.cpython-310-x86_64-linux-gnu.so _gi_cairo.cpython-311-x86_64-linux-gnu.so

sudo cp _gi.cpython-310-x86_64-linux-gnu.so _gi.cpython-311-x86_64-linux-gnu.so

编译安装的python使用此方法无法解决

最好不要更改系统默认python

https://stackoverflow.com/questions/56218562/how-to-fix-modulenotfounderror-no-module-named-apt-pkg

https://askubuntu.com/questions/1301461/modulenotfounderror-no-module-named-apt-pkg-whilst-running-apt-update

https://blog.csdn.net/yulinxx/article/details/125472350

Refer To

https://ubuntuhandbook.org/index.php/2021/10/compile-install-python-3-10-ubuntu/

https://ubuntuhandbook.org/index.php/2022/10/python-3-11-released-how-install-ubuntu/

https://towardsdatascience.com/installing-multiple-alternative-versions-of-python-on-ubuntu-20-04-237be5177474