Poetryを使った仮想環境構築メモ

Python

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 # 仮想環境から出る
プロフィール
この記事を書いた人

30代半ばで未経験でプログラマーに転職し、日々奮闘中です
プログラミング、AI、NLP、キャリア関連などで少しでも役に立てる情報を発信していきます

ユウをフォローする
PythonUncategorized
ユウをフォローする

コメント

タイトルとURLをコピーしました