1. 程式人生 > >切換Ubuntu預設python版本的兩種方法

切換Ubuntu預設python版本的兩種方法

你可以按照以下方法使用 ls 命令來檢視你的系統中都有那些 Python 的二進位制檔案可供使用。

?
1 2 $ 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 版本資訊:

?
1 2 $ python --version Python 2.7.8

1、基於使用者修改 Python 版本:

想要為某個特定使用者修改 Python 版本,只需要在其 home 目錄下建立一個 alias(別名) 即可。開啟該使用者的 ~/.bashrc檔案,新增新的別名資訊來修改預設使用的 Python 版本。

?
1 alias python= '/usr/bin/python3.4'

一旦完成以上操作,重新登入或者重新載入 .bashrc 檔案,使操作生效。

?
1 $ . ~/.bashrc

檢查當前的 Python 版本。

?
1 2 $ python --version Python 3.4.2

2、 在系統級修改 Python 版本

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

?
1 2 # update-alternatives --list python update-alternatives: error: no alternatives for python

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

?
1 2 3 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,所以update-alternatives 命令會自動將它設定為預設 Python 版本。

?
1 2 # python --version Python 3.4.2

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

?
1 2 3 # update-alternatives --list python /usr/bin/python2 .7 /usr/bin/python3 .4

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

?
1 # update-alternatives --config python

?
1 2 # python --version Python 2.7.8

3、移除替代版本

一旦我們的系統中不再存在某個 Python 的替代版本時,我們可以將其從 update-alternatives 列表中刪除掉。例如,我們可以將列表中的 python2.7 版本移除掉。

?
1 2 3 4 # 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

方法2、移除軟連線

?
1 2 3 rm -rf /data/logs   ln -s /temp/logs /data/logs

解決軟連線ln報錯-bash: /usr/local/bin/mysql: Too many levels of symbolic links

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。