この記事の目的
用途に合わせたPythonの環境をすばやく構築したい、そんな時のための手順を、備忘を兼ねて書き記します。
なお、本記事執筆時点(2021/02/27)での情報となります。AWSのサービス内容は常にアップデートされるため、内容が合致しない場合はご了承下さい。
AWSでUbuntuインスタンスを作成
本記事ではAWSの無料利用枠の範囲で設定を行います。
また、AWSのアカウント取得やログインについては割愛します。
1. AWSでインスタンスを選択し設定を行う











(12)既存のキーペアまたは新しいキーペアを選択し、インスタンスの作成を実行して下さい。
インスタンスの作成手続きは以上です。
2. 必要なビルドツール・ライブラリをインストールする
(1)作成したインスタンスにログインします。
SSHツールを使用し作成したインスタンスへログインします。
ここではTera Termを使用しました。ログインの仕方はAWSの一般的な手順となりますのでここでは省略します。

(2)以下を実行して必要なライブラリをインストールします。
sudo apt update
sudo apt install build-essential libbz2-dev libdb-dev libreadline-dev libffi-dev libgdbm-dev liblzma-dev libncursesw5-dev libsqlite3-dev libssl-dev zlib1g-dev uuid-dev tk-dev
バージョンを指定してPythonをソースからインストール
1. Pythonのソースをダウンロードする
(1)Pythonの公式サイトへアクセスします。
AWSインスタンスではなく、ローカルPC端末のブラウザでアクセスします。
Python公式サイト
https://www.python.org/



(5)AWSインスタンスのプロンプトで、取得したURLからソースをダウンロードします。
プロンプトでは以下のように実行してソースを取得します。
wget https://www.python.org/ftp/python/3.9.2/Python-3.9.2.tgz

(6)ソースを解凍します。
取得したファイルを以下のコマンドで解凍します。
tar -xvf Python-3.9.2.tgz
2. Pythonをインストールする
(1)解凍後、以下のコマンドでPythonフォルダへ移動します。
cd Python-3.9.2/
(2)以下の各コマンドを順次実行し、インストールを行います。
./configure
make
sudo make install

(3)pipを使用するため、以下のコマンドでpipライブラリをインストールします。
sudo apt install python-pip
もし上記のコマンドでpipのインストールができない場合は、以下も試してみて下さい。
python -m pip install pillow # ... (※)

/home/ubuntu/Python-3.9.2/python -m pip install --upgrade pip

PATH=$PATH:/home/ubuntu/.local/bin

(4)以下のコマンドでPythonのバージョンを確認します。
想定通りのバージョンが表示されればOKです。
./python -V


次のようにコマンドを実行します。
sudo ln -s /home/ubuntu/Python-3.9.2/python /usr/bin/python
上書きエラーが出る場合は、強制実行オプション[-f]を付けて実行します。
以上でインストールは完了です。
Pythonコマンドでバージョンの確認を行って下さい。
Jupyter Labのインストール
1. Jupyter Labをインストールする
Jupyter Labは以下のコマンドでインストールします。
pip install jupyterlab

2. ブラウザでJupyter Labにアクセスするための設定
AWSインスタンス上にJupyter Labをインストールした場合は、Jupyter Labを実行した後、例えば自宅などの外部ネットワークからアクセスすることになります。この場合、以下のような設定が必要になります。
(1)Jupyter Labの設定ファイルを作成します。
以下のコマンドを実行して下さい。 /home/ubuntu/.jupyter/フォルダ配下に「jupyter_lab_config.py」というファイルが作成されます。
jupyter lab --generate-config
(2)設定ファイルを修正します。
viなどのエディタを使用して、上記の設定ファイルを開きます。

(4)内部プロセスがブラウザを起動しようとする処理を停止します。
Jupyter Labを起動すると、内部プロセスにおいてブラウザを起動しようとします。
この処理は不要なので、設定をFalseにします。

(5)設定が終わったら、保存して閉じます。
3. Jupyter Labを起動する
以下のコマンドでJupyter Labを起動します。
jupyter lab --allow-root

4. Jupyter Labにアクセスする
Jupyter Labにアクセスするには、上記の画像の赤枠部分のURLを使用します。
ただし、このURLのドメイン部分はローカルドメインなので、AWSの「パブリック IPv4 DNS」などに置き換える必要があります。

ローカルPCでブラウザを開き、上記のURL及びパブリック IPv4 DNSから成るURLを入力し、画面を表示することで、Jupyter Labの画面を表示することができます。
<注意>
・プロトコルはhttpのままですので、セキュリティを確保するためにhttpsに変更することをお薦めします。
・AWSインスタンスのセキュリティグループにポート:8888の設定を入れておく必要があります。
・Jupyter Labへアクセスするための認証がかかっていない状態です。Jupyter Labの認証機能を有効にすることをお薦めします。
ご意見など
ご意見、間違い訂正などございましたらお寄せ下さい。