LoginSignup
2
6

More than 1 year has passed since last update.

MacでPython環境作るならHomebrew + asdf + Poetryの組み合わせがいいかもしれない

Last updated at Posted at 2022-03-31

Python環境の構築方法には、

  • インストーラで本体をインストールしたり、
  • Homebrewから本体をインストールしたり、
  • HomebrewからインストールしたPyenvから本体をインストールしたり、
  • HomebrewからインストールしたAnyenvからインストールしたPyenvから本体をインストールしたり、
  • requirements.txtでパッケージを管理したり、
  • pipenvでパッケージを管理したり、

様々な構築の仕方がありどれが最適なのかよく分かりません。
そこで2022年3月現在で一番それっぽいPython環境の構築方法を調べてみました。
あくまで自分調べなのでこれより良い方法がある可能性もあります。一つの参考として使ってください。

結論

Homebrew(パッケージ管理) + asdf(実行環境管理) + Poetry(仮想環境・ライブラリ管理)の構成が強そう

なので、

  • Homebrewからasdfをインストールし、
  • asdfからPython本体をインストールし、
  • Poetryをインストールし、
  • Poetryで仮想環境を構築してパッケージ管理をします。

手順

1.Homebrewのインストール

$ /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

2.asdfのインストール

$ brew install asdf

3.asdfのパスを通す
4.asdfでPythonプラグインを追加

$ asdf plugin-add python

5.asdfでインストールできるPythonのバージョンを確認

$ asdf list-all python

6.asdfでPythonをインストール

$ asdf install python 3.10.4

7.asdfでインストールしたバージョンをグローバル(ローカル)に指定

$ asdf global python 3.10.4 # ローカルに指定したいときは"asdf local"を代わりに実行
$ asdf reshim python

8.シェル再起動
9.Pythonのバージョンが反映されていることを確認

$ python -V
Python 3.10.4

10.Poetryをインストール

$ curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python -

11.Poetryでプロジェクトディレクトリ内に設定ファイルpyproject.tomlを作成

$ poetry init

以上でHomebrew + asdf + Poetry が構築できました。

各ツールについて

Homebrew

  • macOS用でデファクトになっているパッケージマネージャ
  • ターミナルからいろんなソフトをインストールできる

asdf

  • ランタイムバージョンマネージャ
  • いろいろな言語をバージョン指定してインストールできる

Poetry

  • Pythonの仮想環境・パッケージマネージャ
  • 作成した仮想環境内にパッケージをインストールし、仮想環境上でPythonスクリプトを実行できる

基本的な使い方

$ poetry add [package]

して

$ poetry run [command]

するだけで仮想環境内でのコマンド実行ができます。
その他のコマンドはヘルプか公式ページを参照ください。

まとめ

2022年3月現在だとHomebrew + asdf + Poetryの構成でPython環境を作るのがつよそう

以上です。対戦ありがとうございました。

2
6
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
2
6