1. 程式人生 > >Ubuntu18.04下完美切換Python版本

Ubuntu18.04下完美切換Python版本

ubuntu18.04版本,python版本python2.7,python3.5,python3.6

因為安裝一些庫會安裝到python3.6上,而預設使用的是python2.7,使用python3,預設會使用python3.5,無法呼叫安裝包。

解決方法:

一,使用python xx.py執行程式時,加上版本號。比如python3.6 xx.py

二,1,要以root身份操作

[email protected]:~$ sudo su

2,確認本機下的python預設版本。調出終端,輸入python即可檢視預設的版本:

[email protected]:/home/yz# python
Python 3.6.5 (default, Apr  1 2018, 05:46:30) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()
[email protected]
:/home/yz# python2.7 Python 2.7.15rc1 (default, Apr 15 2018, 21:51:34) [GCC 7.3.0] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> exit() [email protected]:/home/yz# python3 Python 3.6.5 (default, Apr 1 2018, 05:46:30) [GCC 7.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> exit()
[email protected]
:/home/yz# python3.5

3,如何切換這兩個版本以及切換預設的python版本:

我們可以使用 update-alternatives 來為整個系統更改Python 版本。以 root 身份登入,首先羅列出所有可用的python 替代版本資訊:

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

如果出現以上所示的錯誤資訊,則表示 Python 的替代版本尚未被update-alternatives 命令識別。想解決這個問題,我們需要更新一下替代列表,將python2.7 和 python3.6放入其中。

​
# 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.4 to provide /usr/bin/python (python) in auto mode

​

--install 選項使用了多個引數用於建立符號連結。最後一個引數指定了此選項的優先順序,如果我們沒有手動來設定替代選項,那麼具有最高優先 級的選項就會被選中。這個例子中,我們為/usr/bin/python3.4 設定的優先順序為2,所以update-alternatives 命 令會自動將它設定為預設 Python 版本。

# python --version
Python 3.5.2

接下來,我們再次列出可用的 Python 替代版本。

# update-alternatives --list python
/usr/bin/python2.7
/usr/bin/python3.5

現在開始,我們就可以使用下方的命令隨時在列出的 Python 替代版本中任意切換了。

(這一步是最關鍵的)

# update-alternatives --config python

下面就簡單了,會提示你輸入序號,你想用哪個版本為預設,就輸入序號就可以了!

結束!