31
20

More than 3 years have passed since last update.

Ubuntuでpythonのバージョンを切り換える

Posted at

pythonのバージョンを管理したり切り替える方法です

現在使う設定になっているpythonのバージョンを確認

$ python --version
Python 2.7.17

確認すると、python3を使いたいのですがpython2系の設定になっているようです

インストールされているpythonのバージョンと場所を確認

$ which python    #すべてのpythonがインストールされている場所を確認
/usr/bin/python    #/usr/bin以下にあるようです
$ ls /usr/bin/ | grep python    #/usr/bin/以下にインストールされている全pythonのバージョンを確認
python2
python2.7
python3
python3.6
python3.6-config
python3-config

update-alternativesが存在することを確認

update-alternativeはpythonのバージョン管理を行います。

$ which update-alternatives
/usr/bin/update-alternatives

pythonのバージョン登録・管理

登録されているpythonのバージョンや優先順位を見ることができます

$ sudo update-alternatives --config python
update-alternatives: error: no alternatives for python    #まだpythonが登録されていない状態です

pythonのバージョンを登録します
sudo update-alternatives --install [pythonの場所] python [pythonの場所][バージョン] [優先順位の数字]
今回はpython3.6と2.7を登録してみます

$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 1    #python3.6を優先順位1で登録
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python2.7 2    #python2.7を優先順位2で登録

登録されたpythonのバージョンやリストの順、優先順位を確認

$ update-alternatives --config python
There are 2 choices for the alternative python (providing /usr/bin/python).

  Selection    Path                Priority   Status
------------------------------------------------------------
  0            /usr/bin/python2.7   2         auto mode
* 1            /usr/bin/python2.7   2         manual mode
  2            /usr/bin/python3.6   1         manual mode
Press <enter> to keep the current choice[*], or type selection number: 2    #python3.6を使用したいのでSelectionの2を入力
update-alternatives: using /usr/bin/python3.6 to provide /usr/bin/python (python) in manual mode
$ python --version    #使用する設定になっているpythonのバージョンを確認
Python 3.6.9

無事python3系に切り替えられました!

31
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
31
20