130
155

More than 1 year has passed since last update.

理系大学生のためのPython環境のススメ

Last updated at Posted at 2023-05-24

この記事は前回の続きです。
VScode, WSL, Docker Desktopの導入については前回の記事を参照してください。
逆に言えばVScode, WSL, Docker Desktopが導入できていれば前回は読まずともOK

一旦コンテナから出て、プロジェクトを開きます。
前回から引き続いてやる人は .devcontainerフォルダを削除しておいてください

Dockerfileを作成

プロジェクトルートにDockerfileを作成します。

Dockerfile
FROM python:slim

RUN apt-get update && \
    pip install --upgrade pip

COPY ./requirements.txt .

RUN pip install -r requirements.txt

解説

Dockerfile
FROM python:slim

slimイメージを選択しています。通常イメージだとかなり重たくなってしまう。。。

Dockerfile
RUN apt-get update && \
    pip install --upgrade pip

イメージのアップデートとpipをアップデートしています。

Dockerfile
COPY ./requirements.txt .

RUN pip install -r requirements.txt

必要パッケージを書き出して、インストールしています。requirements.txtは次で説明します。

必要ライブラリをまとめる

プロジェクトにrequirements.txtを作成します。中身は以下の通りです。

requirements.txt
ipykernel
numpy
pandas
matplotlib
scipy

ここは適宜追加してください。必要なライブラリがあったら、pip installrequirements.txtに追記することを忘れないでください。

ipykernel: notebookを実行するのに必要なカーネルパッケージ

コンテナのビルド

コマンドパレットからDev Containers: Reopen in Containerを選択し、Dockerfileからを選択しましょう。
image.png

コンテナのビルドが始まり、少し待つとコンテナでフォルダが開きます。

拡張機能の導入

導入方法

拡張機能をインストールしたら、歯車マークをクリックし、devcontainer.jsonに追加を選択します。
image.png

必須

  • Python
  • Jupyter

おすすめ

  • Error lens

    • コードの静的チェック結果を可視化してくれます。
      image.png
  • Code Spell Checker

    • 英単語のスペルをチェックしてくれます。ignoreする単語をいちいち追加するのが面倒な人は消してもいい。
  • autoDocstring

    • ドキュメントの文章テンプレートを生成します。関数とか凝って作らない人はいらないかも。
  • indent-rainbow

    • インデントを見やすくしてくれます。
      image.png
  • Office Viewer(Markdown Editor)

    • エクセルファイルを普通に見れるようになります。

Github Copilotについて

学生であればGithub Proに無料で登録でき、VScodeをGithubに紐付けることでGithub Copilot拡張機能をインストールすることで自動でコードを補完してくれます。死ぬほど便利です。

参照 【GitHub】学生申請をして無料でGitHub Copilotを使う

おすすめ設定

基本的に設定はワークスペースのものを編集したほうがいいです。フォルダーに.vscodeというフォルダができ、設定がフォルダ単位で管理できます。
Ctrl+,で設定を開き、ワークスペースタブを開き、次の設定を変えると良いです。

  • Notebook > Format On Save
    • 編集を保存すると自動でフォーマットしてくれます。
      image.png
  • Notebook > Output: Scrolling
    • 出力が長かった場合にスクロールで全文表示できるようになります。
  • Python › Formatting: Provider
    • フォーマッタを選択できます。僕はBlackフォーマッタが好きです。

最後に

いろいろ設定が変わったと思うので、コンテナをリビルドしましょう。
Ctrl+Shift+Pでコマンドパレットを開き、キャッシュなしでリビルドをしましょう。
image.png

※たまに失敗しますがそのときは焦らず再試行をしてください。再起動もしたほうがいいかも

つぎからは、フォルダーをVScodeで開き、右下に出てくるコンテナで再度開くをクリックして環境に接続してください。

最終的には多分こんな感じ

.devcontainer/devcontainer.json
// For format details, see https://aka.ms/devcontainer.json. For config options, see the
// README at: https://github.com/devcontainers/templates/tree/main/src/docker-existing-dockerfile
{
	"name": "Existing Dockerfile",
	"build": {
		// Sets the run context to one level up instead of the .devcontainer folder.
		"context": "..",
		// Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename.
		"dockerfile": "../Dockerfile"
	},
	"customizations": {
		"vscode": {
			"extensions": [
				"usernamehw.errorlens",
				"njpwerner.autodocstring",
				"oderwat.indent-rainbow",
				"ms-toolsai.jupyter",
				"ms-python.python",
                "cweijan.vscode-office"
                "ms-python.black-formatter"
			]
		}
	}
	// Features to add to the dev container. More info: https://containers.dev/features.
	// "features": {},
	// Use 'forwardPorts' to make a list of ports inside the container available locally.
	// "forwardPorts": [],
	// Uncomment the next line to run commands after the container is created.
	// "postCreateCommand": "cat /etc/os-release",
	// Configure tool-specific properties.
	// "customizations": {},
	// Uncomment to connect as an existing user other than the container default. More info: https://aka.ms/dev-containers-non-root.
	// "remoteUser": "devcontainer"
}
.vscode/settings.json
{
    "notebook.formatOnSave.enabled": true,
    "notebook.output.scrolling": true,
    "python.formatting.provider": "black"
}
Dockerfile
FROM python:slim

RUN apt-get update && \
    pip install --upgrade pip

COPY ./requirements.txt .

RUN pip install -r requirements.txt
requirements.txt
black
ipykernel
numpy
pandas
matplotlib
scipy
130
155
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
130
155