3
1

Dev Containerとpoetryを使って開発環境を構築してみる。

Posted at

前提

  • 開発環境: VSCode の Dev Containers
  • パッケージ管理: Poetry
  • Dockerが自分のPC上で稼働していること

作業

Dev Containerの導入

Command + Shift + Pでパレットを開き、以下のように選択する。
image.png

image.png

image.png

image.png

すると、.devcontainer/devcontainer.jsonが作成されるので、ここのpoetryのバージョンを追記する。

.devcontainer/devcontainer.json

{
	"name": "Python 3",
	"image": "mcr.microsoft.com/devcontainers/python:1-3.12-bookworm",
	"features": {
		"ghcr.io/devcontainers-contrib/features/poetry:2": {
			"version": "1.7.1"    // ここを追加
		}
	}

↑を追記した後、以下のようにReopenする。

image.png

すると、Dev Containerで設定したバージョンの環境が出来上がるので、試しに以下のようにコマンドを打ってみる。

$ uname
Linux
$ python --version
Python 3.12.1
$ poetry --version
Poetry (version 1.7.1)

poetryの設定

次に、poetryの設定をしていく。

$ poetry init
# 質問は全てEnterキーでスキップ

↑のコマンドを叩くと、pyproject.tomlファイルが作成される。

pyproject.toml

[tool.poetry]
name = "udemy-llm-apps"
version = "0.1.0"
description = ""
authors = ["atsudora <atsudorasan@gmail.com>"]
readme = "README.md"

[tool.poetry.dependencies]
python = "^3.12"

[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"

ついでにREADME.mdファイルも手動で作成しておく。
pyproject.tomlにREADMEを参照する記述があるため。

次に、poetryの設定ファイルを作成する。

$ poetry config virtualenvs.in-project true --local

↑のコマンドを叩くと、poetry.tomlというファイルが作成される。

poetry.toml

[virtualenvs]
in-project = true

※これはこのディレクトリ配下にpythonパッケージが置かれることを記述している

poetryで用意した環境でpythonバージョン確認

$ poetry run python --version
Python 3.12.1

streamlitを試してみる

poetryにstreamlitをインストールする

$ poetry add streamlit@1.30.0

hello.pyファイルを作成して以下のように記述する

import streamlit as st

st.title("hello world")
$ poetry run streamlit run hello.py

image.png

Tips

途中でBlack formatterなどの拡張機能を入れた場合

image.png

.devcontainer/devcontainer.json

{
	"name": "Python 3",
	"image": "mcr.microsoft.com/devcontainers/python:1-3.12-bookworm",
	"features": {
		"ghcr.io/devcontainers-contrib/features/poetry:2": {
			"version": "1.7.1"
		}
	},
    // 以下が追加されている
	"customizations": {
		"vscode": {
			"extensions": [
				"ms-python.black-formatter"
			]
		}
	}

保存時に自動でフォーマットする方法

.vscode/settings.json

{
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "ms-python.black-formatter"
}
3
1
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
3
1