ubuntu 20.04 自由切换 python 的版本

问题描述

  • 当前 ubuntu 20.04 默认安装了多个 python 的版本,执行 python 时,默认版本是 Python 2.7.18
c 复制代码
zhangsz@zhangsz:~$ python
Python 2.7.18 (default, Jul  1 2022, 12:27:04)
[GCC 9.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
  • 如何更改切换 python 对应的 python 版本,比如 执行 python 时 打开的是 Python 3.8.10

  • 为何需要切换 python 对应的版本,就是有的应用,比如 repo 必须 使用 Python 3.x 的版本,而有的 sdk 编译系统 就使用 python 2.x 的版本,造成需要 python 对于的版本在 python 2.xpython 3.x 之间自由切换,而不是 安装卸载操作

切换方法

  • 对比了多种方法,发现使用 update-alternatives 是最方便的方法,胜过使用 文件软链接。

  • 我当前的 Ubuntu 20.04 安装了两个版本的 python,分别是 python2.7 与 python3.8

  • 操作方法:配置 python,这里使用 update-alternatives --install

c 复制代码
sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.8 2
  • 此时执行 sudo update-alternatives --config python 进行 python 版本的切换操作
c 复制代码
zhangsz@zhangsz:~$ sudo update-alternatives --config python
[sudo] password for zhangsz:
There are 3 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2     100       auto mode
  1            /usr/bin/python2     100       manual mode
* 2            /usr/bin/python2.7   1         manual mode
  3            /usr/bin/python3.8   2         manual mode

Press <enter> to keep the current choice[*], or type selection number: 3
  • 以上,注意选择 Selection 下面的索引号,比如当前 2 对应 /usr/bin/python2.7,而 3 对应 /usr/bin/python3.8

  • 如果当前 是 python 执行后是 python 2.7,想执行 python 时执行 python 3.8,就 选择 3,这样执行 python 就执行
    python 3.8

  • 通过 sudo update-alternatives --config python 可以在多个 python 版本中自由的切换。

  • 当前验证下来,可以自由正确切换 python 默认执行的版本

小结

  • 如果想自由切换 python 执行的 python 版本,首先 ubuntu 系统需要安装多个 python版本,比如 python 2.xpython 3.x

  • 使用 update-alternatives --install 安装 python 版本的配置【列表】

  • 使用 update-alternatives --config 可以自由切换 python 默认执行的版本

  • update-alternatives 不只是用于切换 python 的默认执行脚本,理论上可以用于切换其他软件的版本,操作方法一致。

相关推荐
繁星日月5 分钟前
利用docker搭建漏洞环境,使用SSRF+Redis写入centos以及ubuntu的公钥,实现免密登录
redis·安全·ubuntu·docker·容器·centos·渗透
镜花照无眠9 分钟前
python破解字母已知但大小写未知密码
开发语言·python
程序无涯海13 分钟前
Python爬虫教程第1篇-基础知识
开发语言·爬虫·python·网络爬虫
Learning改变世界16 分钟前
ubuntu24.04按关键字卸载不需要的apt包
ubuntu
家有狸花24 分钟前
PYTHON自学笔记(一)vscode配置
笔记·vscode·python
鸽芷咕1 小时前
【python学习】快速了解python基本数据类型
开发语言·python·学习
秋刀鱼_(:з」∠)_别急1 小时前
如何获取歌曲id---cloudmusic
后端·爬虫·python·计算机网络·ajax·okhttp·xhr
杰哥在此1 小时前
Python面试题:如何在 Python 中读取和写入 JSON 文件?
开发语言·python·面试·json·编程
我是陈泽1 小时前
AI教你如何系统的学习Python
开发语言·数据结构·人工智能·python·学习·青少年编程
落798.1 小时前
【植物大战僵尸杂交版】获取+存档插件
python·游戏·github