nabeo がピーしているブログ (仮)

どーも、nabeop です

Node.js の grpc パッケージのインストール時に python で gyp が見つからなくてエラーになる時の対処

手元環境の python を 3.12 系に更新したあとに Node.js で grpc パッケージを入れようとすると

│ Traceback (most recent call last):
│   File "/Users/nabeo/.cache/node/corepack/pnpm/8.15.3/dist/node_modules/node-gyp/gyp/gyp_main.…
│     import gyp  # noqa: E402
│     ^^^^^^^^^^
│   File "/Users/nabeo/.cache/node/corepack/pnpm/8.15.3/dist/node_modules/node-gyp/gyp/pylib/gyp…
│     import gyp.input
│   File "/Users/nabeo/.cache/node/corepack/pnpm/8.15.3/dist/node_modules/node-gyp/gyp/pylib/gyp…
│     from distutils.version import StrictVersion
│ ModuleNotFoundError: No module named 'distutils'

こういうエラーで失敗してしまう。エラーメッセージでググるpython 3.12 から distutils は削除されたので、python の packaging を入れなさいという issue が nodejs/node-gyp であった。

もしくは npm_config_python 環境変数python 3.11 のパスを設定すると回避もできるらしい。とりあえずの対処としては npm_config_python 環境変数で逃げるでもよいけど、これからのことを考えるといつまでも python 3.11 に依存したくないので、python 3.12 でちゃんと使えるようにしたい。

homebrew では python の packaging は python-packaging として提供されていて、このエラーが発生時している時点でちゃんと入っていた。

% brew info python-packaging
==> python-packaging: stable 24.0 (bottled)
Core utilities for Python packages
https://packaging.pypa.io/
/opt/homebrew/Cellar/python-packaging/24.0 (53 files, 372KB) *
  Poured from bottle using the formulae.brew.sh API on 2024-03-25 at 10:36:03
From: https://github.com/Homebrew/homebrew-core/blob/HEAD/Formula/p/python-packaging.rb
License: Apache-2.0 or BSD-2-Clause
==> Dependencies
Build: python-flit-core ✘, python@3.11 ✔, python@3.12 ✔
==> Analytics
install: 19,387 (30 days), 63,842 (90 days), 205,027 (365 days)
install-on-request: 821 (30 days), 1,497 (90 days), 3,796 (365 days)
build-error: 24 (30 days)
% brew list python-packaging
/opt/homebrew/Cellar/python-packaging/24.0/lib/python3.11/ (23 files)
/opt/homebrew/Cellar/python-packaging/24.0/lib/python3.12/ (23 files)
%

実は python の setuptools も必要というオチだったので、brew install python-setuptools で setuptools も入れて、python 3.12 の環境でも Node.js の grpc パッケージのインストールができるようになった。