另一个适用于不同(以及较旧)版本的Ubuntu的选项是“alternatives”系统,可以使用命令行
update-alternatives
(应该已安装)或GUI
galternatives
(默认未安装)。当您有多个版本或完全不同但兼容的实现(例如编译器、编辑器)时,它允许您配置您的“首选”版本(请参见此示例:
update-alternatives --get-selections
)。
要查看当前默认的Python版本(注意:这些是指向特定版本的符号链接):
$ type python python2 python3
python not found
python2 is /usr/bin/python2
python3 is /usr/bin/python3
通常(就是总是,没有例外)你希望默认的
python
是
python2
,出于兼容性的考虑(否则
会破坏apt和其他系统工具!),只有在真正需要Python3时才显式地调用
python3
。
要查看当前为
python
配置的可选项:
$ sudo update-alternatives --list python
error: no alternatives found
如果找到了替代方案,请跳过以下步骤(参见下面的--config)。否则,我们可以将python2和python3都配置为"alternatives"命令,并且您可以在它们之间切换(或者只需在此处设置python2并完成;其余部分是为了完整性和练习而提供):
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python2 40
using /usr/bin/python2 to provide /usr/bin/python (python) in auto mode
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 20
using /usr/bin/python3 to provide /usr/bin/python (python) in auto mode
$ type python
/usr/bin/python
$ python --version
Python 2.7.18
重要!如果您的默认Python显示为python3
,请在此更改为python2
,否则apt
和其他系统工具可能会出现问题!
要使用update-alternatives
更改当前选择的版本,请按照以下步骤进行,并选择您想要的版本:
$ sudo update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).
Selection Path Priority Status
------------------------------------------------------------
* 0 /usr/bin/python2 40 auto mode
1 /usr/bin/python2 40 manual mode
2 /usr/bin/python3 20 manual mode
Press <enter> to keep the current choice[*], or type selection number: 0
要完全删除所有的
python
备选配置(例如,重新开始,或者如果出现任何奇怪的情况,撤销所有操作):
$ sudo update-alternatives --remove-all python
python
和python3
?但它们两个本来就已经被安装了(比如说Lubuntu 18.04 LTS,它自带的版本是Python 3.6)。你是怎么安装它们的?你有没有移除或替换掉预装的版本?我怀疑你的问题可能出在$PATH上,也就是说你移除了原本在路径中的预装版本,安装到其他地方或者将$PATH修改成了不同于默认设置的值。 - guiverchistory
可以帮助你回忆起来。在我的 Lubuntu 上,whereis python
告诉我它的位置,而命令echo $PATH
则显示了被搜索的命令目录列表。我所建议的可能在你的系统上出现了损坏,或者如果你是从源代码安装的(这就是我为什么问你如何安装的原因),它可能被安装在$PATH
默认之外。如果我输入python --version
,我的系统会回应 2.7.16,而python3 --version
则回应 3.7.3(注意:我没有使用 18.04 版本,所以很可能是较新的版本)。你有删除任何东西吗?它是如何安装的? - guivercpython
调用Python 3的方法,但是你为什么不能直接运行python3
呢?如果有原因的话,值得解释一下是什么原因。 - Colin Watson