🐍

site-packages の場所を確認する

2021/08/16に公開

Python を使っているとき、モジュール(ライブラリ)がインストールされておらず、 ImportError になることがある。 Python は site-packages というディレクトリ以下にライブラリをインストールする。

venvpyenv などの仮想環境を使っていると、実行している python がどこを参照しているのかわからなくなる。

そのときに便利なのが、 site モジュール。 site.getsitepackages() で参照可能な site-packages をリストアップできる。

公式ドキュメント: https://docs.python.org/ja/3/library/site.html#site.getsitepackages

REPL

$ python
Python 3.9.6 (default, Jul 21 2021, 20:17:34) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import site
>>> site.getsitepackages()
['/home/tamanobi/ghq/github.com/tamanobi/graphene/.venv/lib/python3.9/site-packages']

One-liner

$ python -c "import site;print(site.getsitepackages())"
['/home/tamanobi/ghq/github.com/tamanobi/graphene/.venv/lib/python3.9/site-packages']

パッケージのインストールを確認する

特定のパッケージがインストールされているかどうかを知るだけなら、 pip show を使えば簡単に見つかる。公式ドキュメント: https://pip.pypa.io/en/stable/cli/pip_show/#pip-show

Location という項目に配置されている site-packages のパスが表示される。

$ pip show django
Name: Django
Version: 3.2.6
Summary: A high-level Python Web framework that encourages rapid development and clean, pragmatic design.
Home-page: https://www.djangoproject.com/
Author: Django Software Foundation
Author-email: foundation@djangoproject.com
License: BSD-3-Clause
Location: /home/tamanobi/ghq/github.com/tamanobi/graphene/.venv/lib/python3.9/site-packages
Requires: pytz, asgiref, sqlparse
Required-by: graphene-django

Discussion