poetryを使って仮想環境を作る際、都度、調べていたので、本記事でまとめようと思います。
Poetryのインストール
macの場合、以下のコマンドでPoetryをインストールできます。
curl -sSL https://install.python-poetry.org | python3 -
プロジェクトのセットアップ
新規にプロジェクトを作成する場合は以下を実行します。
poetry new poetry-demo
既にあるプロジェクトをpoetry管理下に置きたい場合は以下のようにします。
cd poetry-demo
poetry init
仮想環境を作成
poetry install
を実行することで、仮想環境を作成できます。
cd poetry-demo
poetry install
特定のpythonのバージョンを使って仮想環境を作成したい場合は以下のようにします(参考)。
cd poetry-demo
poetry env use python3.10
pyproject.tomlの設定によっては以下のエラーが出るかもしれません。
The specified Python version (3.10.11) is not supported by the project (^3.11).
Please choose a compatible version or loosen the python constraint specified in the pyproject.toml file.
その場合、pyproject.tomlを修正します。
[tool.poetry.dependencies]
# 修正前
python = "^3.11"
# 修正後
python = "^3.10"
パッケージの追加
poetry add <package-name>
仮想環境で実行
特定のコマンドを実行して仮想環境からすぐに抜けたい場合は以下のようにします。
poetry run python <python-file> # python fileの実行
poetry pytest # 依存関係で追加したパッケージに含まれるコマンドを実行
仮想環境に入りたい場合は以下のようにします。
poetry shell # 仮想環境に入る
exit # 仮想環境から出る
コメント