Ubuntu 20.04 自如切换 Python 版本

问题描述

  • 当前 ubuntu 20.04 默认安装了多个 python 的版本,执行 python 时,默认版本是 Python 2.7.18
  • 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

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

  • 作者:张世争

    物联沃分享整理
    物联沃-IOTWORD物联网 » Ubuntu 20.04 自如切换 Python 版本

    发表回复