如何在debian 9 linux上更改默认python版本

Debian 9 配有两个2.73.5python版本。
如果我们尚未安装任何Python包,则只需安装适当的软件包即可:

PYTHON 2 INSTALLATION:
# apt install python
PYTHON 3 INSTALLATION:
# apt install python3

检查默认Python版本

要检查默认Python版本,只需运行python命令并查询其版本:

$python --version
Python 2.7.13

安装python

# python --version
-bash: python: command not found
# apt install python python3

安装后,Python版本2.7是默认值:

$python --version
Python 2.7.13

更新Python备选方案列表

要在默认python版本之间执行系统范围的切换,请使用“updatealternations”命令。

开始时,“updatealternations”命令会抱怨没有可用的python替代方案:

# update-alternatives --list python
update-alternatives: error: no alternatives for python

要安装Python备选方案,请先列出所有可用选项:

$ls /usr/bin/python*
/usr/bin/python  /usr/bin/python2  /usr/bin/python2.7  /usr/bin/python3  /usr/bin/python3.5  /usr/bin/python3.5m  /usr/bin/python3m

接下来,更新待使用的每个版本的Python备选方案列表。
这里,我们使用usr/bin/python2.7和/usr/bin/python3.5版本:

# 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.5 2
update-alternatives: using /usr/bin/python3.5 to provide /usr/bin/python (python) in auto mode

请注意,每个命令末尾的数字表示优先级。数字越大,优先级越高。

我们当前的默认Python版本是“/usr/bin/python3.5,因为它的优先级更高

# python --version
Python 3.5.3

在Python版本之间切换

现在,我们有了更新的Python备选方案列表,可以在任何Python版本之间切换:

# update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).
  Selection    Path                Priority   Status
-----------------------------------------------------------
* 0            /usr/bin/python3.5   2         auto mode
  1            /usr/bin/python2.7   1         bananaal mode
  2            /usr/bin/python3.5   2         bananaal mode
Press <enter> to keep the current choice[*], or type selection number: 1
update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in bananaal mode

选择后:

# python --version
Python 2.7.13

本地用户Python版本

如果我们只需要为某个用户更改Python版本,则可以尝试编辑用户的“.bashrc文件”。

示例:

$python --version
Python 2.7.13
$echo 'alias python="/usr/bin/python3.5"' >> ~/.bashrc
$. .bashrc 
$python --version
Python 3.5.3
日期:2020-07-07 20:56:09 来源:oir作者:oir