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

相关推荐
孟健12 小时前
Karpathy 用 200 行纯 Python 从零实现 GPT:代码逐行解析
python
码路飞14 小时前
写了个 AI 聊天页面,被 5 种流式格式折腾了一整天 😭
javascript·python
曲幽17 小时前
FastAPI压力测试实战:Locust模拟真实用户并发及优化建议
python·fastapi·web·locust·asyncio·test·uvicorn·workers
敏编程21 小时前
一天一个Python库:jsonschema - JSON 数据验证利器
python
前端付豪21 小时前
LangChain记忆:通过Memory记住上次的对话细节
人工智能·python·langchain
databook21 小时前
ManimCE v0.20.1 发布:LaTeX 渲染修复与动画稳定性提升
python·动效
花酒锄作田1 天前
使用 pkgutil 实现动态插件系统
python
前端付豪2 天前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽2 天前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战2 天前
Pydantic配置管理最佳实践(一)
python