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 的默认执行脚本,理论上可以用于切换其他软件的版本,操作方法一致。

相关推荐
Sunshine for you18 分钟前
如何用FastAPI构建高性能的现代API
jvm·数据库·python
阿贵---22 分钟前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python
Red丶哞1 小时前
内网自建Postfix使用Python发送邮件
开发语言·python
小飞菜涅1 小时前
fast-lio2复现
嵌入式硬件·学习·ubuntu
rebekk1 小时前
pytorch custom op的简单介绍
人工智能·pytorch·python
chushiyunen1 小时前
uv使用笔记(python包的管理工具)
笔记·python·uv
曲幽1 小时前
FastAPI状态共享秘籍:别再让中间件、依赖和路由“各自为政”了!
python·fastapi·web·request·state·depends·middleware
风清扬【coder】1 小时前
Anaconda 被误删后抢救手册:数据恢复 + 环境重建应急流程
python·数据恢复·anaconda·环境重建
2401_884563241 小时前
进阶技巧与底层原理
jvm·数据库·python
2401_873204651 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python