3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Poetryのクイックスタート (Linux、macOS、WSL)

Last updated at Posted at 2023-11-21

Poetryでサクッと環境を作成したいとき用の備忘録

インストール

Poetry公式サイト

1. Poetryをインストールする

以下のコマンドで公式インストーラを使ってインストールする。

$ curl -sSL https://install.python-poetry.org | python3 -

2. PATHを通す

インストール後にパスを通すコマンドが出力される。
これをPATHファイルに記述する。

例)シェルがBashの場合

$ echo 'export PATH="/Users/○○○/.local/bin:$PATH"' >> ~/.bashrc

3. 更新する

$ poetry self update

セットアップ方法

1. 初期設定

以下のコマンドを実行し、virtualenvがプロジェクト直下に置かれるようにする。

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

2-a. プロジェクトのセットアップ

Poetry公式サイト

プロジェクトの始め方は2通りあります。
まずは新しくプロジェクトを作成する場合で、以下のコマンドを実行する。

$ poetry new <プロジェクト名>

上記のコマンドを実行すると以下のようなフォルダが生成される。

<プロジェクト名>
├── pyproject.toml
├── README.md
├── poetry_demo
│   └── __init__.py
└── tests
    └── __init__.py

2-b. 既存のプロジェクトでのセットアップ

もう一つは既存のプロジェクトに対してセットアップする方法です。
既存プロジェクトにcdコマンドで移動し、poetry initで初期化する。
pyproject.tomlファイルが生成される。

$ cd pre-existing-project
$ poetry init

3. 仮想環境を有効化し、インストール

初回は以下の2つのコマンドを続けて実行する。

$ poetry shell
$ poetry install

poetry shell.venvが作成し、poetry installpoetry.lockが生成する。

仮想環境の有効化・無効化

Poetry公式サイト

  • poetry shell:仮想環境を起動
  • exit:仮想環境を終了して新しいシェルを終了
  • deactivate:シェルを無くさずに仮想環境を終了

依存関係のインストール・アンインストール

  • poetry install:現在のプロジェクトにある pyproject.toml ファイルを読み込み、依存関係を解決し、インストールする
  • poetry add:pyproject.toml に要求しているパッケージを追加し、インストールする
    • poetry add numpy
  • poetry remove:現在のインストールされたパッケージの一覧からパッケージを削除
    • poetry remove numpy

requirements.txtを作成する

$ poetry export --without-hashes --dev --output requirements.txt
  • --without-hashes:poetry.lockで持っているハッシュを出力しないようにするオプション
  • --dev:dev-dependenciesも含めるというオプション

アンインストール

Poetry公式サイト

以下のコマンドを実行する。

$ curl -sSL https://install.python-poetry.org | python3 - --uninstall
$ curl -sSL https://install.python-poetry.org | POETRY_UNINSTALL=1 python3 -
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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?