Pythonで開発しているとPythonのバージョンを変更したいときが出てきます。特にPythonを学習しているときに参考書等によって使用しているPythonのバージョンが違う場合に変更したいケースが多いですね。あれ?バージョンが違っていてエラーが出てる、、、そんなことが多いです。
Ubuntuでは複数のPythonをインストールしておいて、コマンドで切り替えて使うことができます。これはとても便利な機能です。
Contents
Pythonのバージョン確認
0 1 2 3 |
$ python -V Python 3.7.17 |
Pythonのインストールされている場所を確認
0 1 2 3 |
$ which python /usr/bin/python |
Pythonのバージョン一覧と有効なバージョンの確認
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
$ sudo update-alternatives --config python There are 5 choices for the alternative python (providing /usr/bin/python). Selection Path Priority Status ------------------------------------------------------------ 0 /usr/bin/python3.11 150 auto mode 1 /usr/bin/python3.10 140 manual mode 2 /usr/bin/python3.11 150 manual mode * 3 /usr/bin/python3.7 110 manual mode 4 /usr/bin/python3.8 120 manual mode 5 /usr/bin/python3.9 130 manual mode Press <enter> to keep the current choice[*], or type selection number: |
現在は5つのバージョンがインストールされており、*のついた3番「Python3.7」が有効になっています。最後の行の後に番号を指定してEnterキーを押すと指定した番号のPythonが有効になります。
Pythonをupdate-alternativesに登録
0 1 2 |
$ sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1 |
最後のpython3.7の後にスペースを開けて1を入れているのは、優先順位を1番にするという意味です。