Home ubuntu python多版本切换
Post
Cancel

ubuntu python多版本切换

安装

1
apt-get install python python3 -y

默认情况,默认的python是指向python2的,在/usr/bin目录下

1
2
3
4
5
6
➜  bin ls -al| grep python
lrwxrwxrwx  1 root root           7 4月  15  2020 python -> python2
lrwxrwxrwx  1 root root           9 3月  13  2020 python2 -> python2.7
-rwxr-xr-x  1 root root     3662032 7月   1  2022 python2.7
lrwxrwxrwx  1 root root           9 10月 27 12:48 python3 -> python3.8
-rwxr-xr-x  1 root root     5494584 5月  26 22:05 python3.8

可以看到python链接到的是python2,不过一般切换python版本,我们不会直接去更改链接,会使用update-alternatives来管理

配置和使用update-alternatives管理python版本

查看目前可以管理的python
1
update-alternatives --list python

有可能会直接输出

1
update-alternatives: error: no alternatives for python

表示我们并没有关联任何的python版本

绑定
1
2
update-alternatives --install /usr/bin/python python /usr/bin/python3.8 1
update-alternatives --install /usr/bin/python python /usr/bin/python2.7 2

语法:update-alternatives –install

这时如果再查看,则可以看到已经有了两个python版本了

1
2
/usr/bin/python2.7
/usr/bin/python3.8
切换python版本
1
2
3
4
5
6
7
8
9
10
11
12
13
➜  bin update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

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

Press <enter> to keep the current choice[*], or type selection number: 2
update-alternatives: using /usr/bin/python3.8 to provide /usr/bin/python (python) in manual mode
➜  bin python --version
Python 3.8.10

可以看到,已经切换到了python3了。

删除python选项

update-alternatives –remove 删除对应的选项

update-alternatives –remove-all 删除的所有选项

参考

Ubuntu:Python多版本切换。

This post is licensed under CC BY 4.0 by the author.