M1 MacのPythonデフォルトを3.9にする

2020.12.23

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

もう家にあるパソコン全部捨てていいレヴェルの我がM1 Mac miniの圧倒的パフォーマンスですが、デフォルトシェルがzshになってる割には環境をいい感じにまとめてくれていないため、 python -V と打つと 2.7.x が帰ってきます。

Homebrewをインストール

HomebrewのArm対応についてissue内で少し揉めていましたが、 /opt/homebrew に当面インストールするというプラクティスでとりあえず落ち着いたようです。私はもうx86は忘れるストロングスタイルで通させてもらうので、以下のようにインストールしました。

sudo mkdir /opt/homebrew
sudo chown $USER:admin /opt/homebrew
curl -L https://github.com/Homebrew/brew/tarball/master | tar xz --strip 1 -C /opt/homebrew

.zshrc がないと思うので vi ~/.zshrc で編集してPathを通します。

export PATH=/opt/homebrew/bin:$PATH

brew update、brew doctorを実行すると以下のように怒られますが知ったこっちゃありません。

You are running macOS on a arm64 CPU architecture. We do not provide support for this (yet). Reinstall Homebrew under Rosetta 2 until we support it. You will encounter build failures with some formulae. Please create pull requests instead of asking for help on Homebrew's GitHub, Twitter or any other official channels. You are responsible for resolving any issues you experience while you are running this unsupported configuration.

Python3.9をインストール

最初はhomebrewからインストールしたpyenvで環境を整えようと思いましたが、pyenvの3.9.0はビルドに失敗するので、brew install pythonでやります。別にzshで複数のPython環境をいじることはないですし、やるときはPyCharmを使うからいいんです。

ボトルが用意されていないのでhomebrewからソースビルドをうながされますので、指示に従うと3.9.1がまもなくきれいにインストールされます。

brew info python
python@3.9: stable 3.9.1
Interpreted, interactive, object-oriented programming language
https://www.python.org/
/opt/homebrew/Cellar/python@3.9/3.9.1_1 (8,629 files, 129MB) *
Built from source on 2020-12-22 at 20:40:25
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/python@3.9.rb
License: Python-2.0
==> Dependencies
Build: pkg-config ✔
Required: gdbm ✔, openssl@1.1 ✔, readline ✔, sqlite ✔, xz ✔
==> Caveats
Python has been installed as
/opt/homebrew/bin/python3

Unversioned symlinks `python`, `python-config`, `pip` etc. pointing to
`python3`, `python3-config`, `pip3` etc., respectively, have been installed into
/opt/homebrew/opt/python@3.9/libexec/bin

You can install Python packages with
pip3 install They will install into the site-package directory
/opt/homebrew/lib/python3.9/site-packages

See: https://docs.brew.sh/Homebrew-and-Python
==> Analytics
install: 912,050 (30 days), 1,761,718 (90 days), 1,761,728 (365 days)
install-on-request: 253,748 (30 days), 415,228 (90 days), 415,238 (365 days)
build-error: 0 (30 days)

Unversioned symlinksのくだりで /opt/homebrew/opt/python@3.9/libexec/bin というインストールパスがあるので、さっきの .zshrc を編集してパスを通します。

export PATH=/opt/homebrew/bin:$PATH
export PATH=/opt/homebrew/opt/python@3.9/libexec/bin:$PATH

これで完了です。

which python
/opt/homebrew/opt/python@3.9/libexec/bin/python
python -V
Python 3.9.1