如何在 Debian Linux 上从默认 Python 版本更改为替代 Python 版本
您的 Debian Linux 安装可能包含多个 Python 版本,因此也包含多个 Python 二进制可执行文件,并且可以更改系统正在使用的 python 版本。在本教程中,您将了解如何安装多个版本的 python,以及如何使用 update-alternatives python
命令更改 Debian 上的 python 版本。这将允许您运行各种 Python 程序,包括遗留脚本。请查看以下部分以了解操作方法。
在本教程中您将学习:
如何安装多个python版本
如何在 Debian 上更改 python 版本
在 Debian 上安装 Python
警告
Python 2 已于 2020 年 1 月 1 日停用。您仍然可以安装 Python 2 来运行一些旧脚本,但强烈建议更新到 Python 3(如果可能) ,更新您的脚本以在较新的 Python 版本上运行。
有许多不同版本的 Python 可用。大多数开发人员可能想要安装的两个版本(可在 Debian 的默认存储库中找到)是最新版本的 Python 2 和 3。可以使用以下命令来安装它们。
在 Debian 上安装 Python 2:
$ sudo apt install python2
在 Debian 上安装 Python 3:
$ sudo apt install python3
我使用的是哪个版本的 Python?
您可以运行以下 ls 命令来查找系统上可用的 python 二进制可执行文件:
$ ls /usr/bin/python*
/usr/bin/python /usr/bin/python2 /usr/bin/python2.7 /usr/bin/python3 /usr/bin/python3.4 /usr/bin/python3.4m /usr/bin/python3m
要检查您的默认 python 版本是什么,请执行:
$ python --version
Python 2.7.8
如果该命令不起作用,请尝试使用 python3
命令:
$ python3 --version
根据每个用户更改 python 版本
要根据每个用户更改 python 版本,您只需在用户的主目录中创建一个别名
即可。打开 ~/.bashrc 文件并添加新别名以更改默认的 python 可执行文件:
alias python='/usr/bin/python3.4'
进行上述更改后,重新登录或获取您的 .bashrc
文件:
$ . ~/.bashrc
检查你的默认 python 版本:
$ python --version
Python 3.4.2
使用 update-alternatives python 更改系统范围内的 python 版本
要在系统范围内更改 python 版本,我们可以使用 update-alternatives python 命令。以 root 用户身份登录,首先列出所有可用的 python 替代方案:
# update-alternatives --list python
update-alternatives: error: no alternatives for python
上述错误消息意味着 update-alternatives 命令尚未识别任何 Python 替代方案。因此,我们需要更新替代表并包含 python2.7
和 python3.4
:
# update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
# update-alternatives --install /usr/bin/python python /usr/bin/python3.4 2
update-alternatives: using /usr/bin/python3.4 to provide /usr/bin/python (python) in auto mode
--install
选项采用多个参数,从中可以创建符号链接。最后一个参数指定的优先级意味着,如果没有进行手动替代选择,则将设置具有最高优先级编号的替代。在我们的例子中,我们为 /usr/bin/python3.4
设置了优先级 2,因此 /usr/bin/python3.4
被设置为默认 python通过 update-alternatives
命令自动更新版本。
# python --version
Python 3.4.2
接下来,我们可以再次列出所有 python 替代方案:
# update-alternatives --list python
/usr/bin/python2.7
/usr/bin/python3.4
从现在开始,我们可以随时使用以下命令并输入选择编号在上面列出的 python 替代版本之间切换:
# update-alternatives --config python
# python --version
Python 2.7.8
故障排除
如果我们的系统上不再安装替代的 python 版本,我们可以删除其 update-alternatives
列表。例如,让我们删除 python2.7 版本:
# update-alternatives --remove python /usr/bin/python2.7
update-alternatives: removing manually selected alternative - switching python to auto mode
update-alternatives: using /usr/bin/python3.4 to provide /usr/bin/python (python) in auto mode
结束语
在本教程中,我们了解了如何在 Debian Linux 上的多个 Python 版本之间切换。正如您在此处所看到的,无需删除一个版本的 Python 而转而使用另一个版本,因为您可以同时使用这两个版本。这对于想要为不同版本编写代码的 Python 程序员来说非常方便,使他们能够保留对遗留应用程序的支持,同时仍然按照最新标准进行编码。