チーム開発に必須!Pythonのパッケージ管理ツールPipenvの使い方を解説!

Docker
記事内に広告が含まれています。

PipenvとはPythonのパッケージ(ライブラリ)管理ツールです。Pythonに限らずその他のプログラミング言語でもそうですが、ライブラリを全く使わずに開発することはありません。PipenvはPythonライブラリをインストールしたり、アンインストールしたりすることができ、指定のライブラリのバージョンでインストールすることができます。これにより複数人で開発する場合に、同じライブラリバージョンで開発することができるようになるため、同じ環境を容易に準備することができます。あなたのPython環境にPipenvをインストールして、共同開発ができる環境を整えましょう。

前提条件

  • Docker Desktopのインストールが終わっていることを確認してください。
  • Docker DesktopでなくてもDockerエンジンがインストールされている環境であれば問題ありません。

Docker Desktopのインストールが終わっていない方は、以下記事をご覧ください。

Pythonのインストール

プロジェクトの作成

私の場合プロジェクトのリポジトリをまとめて保存するためのreposというディレクトリをホームディレクトリに作成し、その中に各プロジェクトのディレクトリを作成しています。今回の場合はexampleというプロジェクトを作成しています。

mkdir ~/repos/example

作成した~/repos/exampleディレクトリに移動します。

cd ~/repos/example

gitの初期設定

これらの情報は、今後gitでコミットする際に記録されるユーザー名とメールアドレスになります。プロジェクトを跨いで設定したい場合は–globalオプション、このプロジェクト(今回の場合はexample)に限定したい場合は–localオプションで設定してください。今回はプロジェクトを跨いだ方法で案内しております。

ユーザー名の設定

git config --global user.name "inasan"

メールアドレスの設定

git config --global user.email [email protected]

gitの初期化

gitの初期化を行います。これでgitのバージョン管理下に置かれたことになります。git設定がお済みでない方はgit initする前にこちらの記事を参考にgit設定を済ませてください。

git init

Pythonイメージのダウンロードと起動

docker run -it --rm -v $(pwd):/app --name python-example python:latest /bin/bash

出力結果

PythonのDockerイメージのダウンロード(pull)とともに、Pythonのコンテナが起動し/bin/bashでログインできたことが確認できます。

Unable to find image 'python:latest' locally
latest: Pulling from library/python
5665c1f9a9e1: Already exists
f419b1a62fc8: Already exists
76b4f1810f99: Already exists
1c176cbf6497: Already exists
ba0d9396537e: Already exists
f93cd5cfd8e8: Already exists
cac9244624e2: Already exists
84ab309da70c: Already exists
Digest: sha256:a09f71f4af992ddf9a620330fed343c850c371251be45c3f9bb46ebeca49c9c6
Status: Downloaded newer image for python:latest
root@1aeb98c21829:/#

/appディレクトリへの移動

cd /app

Pythonのバージョン確認

今回python:latest(最新)を指定してしまったので、Pythonバージョンを確認します。

python -V

出力結果

Pythonの3.12.1がダウンロードされたことがわかります。

Python 3.12.1

Pipenvのインストール

Pipenvのインストールは、Pythonコアパッケージに含まれるpipを使う必要があります。

pipenvのインストール

pip install pipenv

出力結果

Collecting pipenv
  Obtaining dependency information for pipenv from https://files.pythonhosted.org/packages/47/74/c08b0560af1ffbb6b94664e082e1560ecf4d83db76d6bf459a1b20e6b831/pipenv-2023.11.17-py3-none-any.whl.metadata
  Downloading pipenv-2023.11.17-py3-none-any.whl.metadata (19 kB)
Collecting certifi (from pipenv)
  Obtaining dependency information for certifi from https://files.pythonhosted.org/packages/64/62/428ef076be88fa93716b576e4a01f919d25968913e817077a386fcbe4f42/certifi-2023.11.17-py3-none-any.whl.metadata
  Downloading certifi-2023.11.17-py3-none-any.whl.metadata (2.2 kB)
Requirement already satisfied: setuptools>=67 in /usr/local/lib/python3.12/site-packages (from pipenv) (69.0.3)
Collecting virtualenv>=20.24.2 (from pipenv)
  Obtaining dependency information for virtualenv>=20.24.2 from https://files.pythonhosted.org/packages/83/22/54b1180756d2d6194bcafb7425d437c3034c4bff92129c3e1e633079e2c4/virtualenv-20.25.0-py3-none-any.whl.metadata
  Downloading virtualenv-20.25.0-py3-none-any.whl.metadata (4.5 kB)
Collecting distlib<1,>=0.3.7 (from virtualenv>=20.24.2->pipenv)
  Obtaining dependency information for distlib<1,>=0.3.7 from https://files.pythonhosted.org/packages/8e/41/9307e4f5f9976bc8b7fea0b66367734e8faf3ec84bc0d412d8cfabbb66cd/distlib-0.3.8-py2.py3-none-any.whl.metadata
  Downloading distlib-0.3.8-py2.py3-none-any.whl.metadata (5.1 kB)
Collecting filelock<4,>=3.12.2 (from virtualenv>=20.24.2->pipenv)
  Obtaining dependency information for filelock<4,>=3.12.2 from https://files.pythonhosted.org/packages/81/54/84d42a0bee35edba99dee7b59a8d4970eccdd44b99fe728ed912106fc781/filelock-3.13.1-py3-none-any.whl.metadata
  Downloading filelock-3.13.1-py3-none-any.whl.metadata (2.8 kB)
Collecting platformdirs<5,>=3.9.1 (from virtualenv>=20.24.2->pipenv)
  Obtaining dependency information for platformdirs<5,>=3.9.1 from https://files.pythonhosted.org/packages/be/53/42fe5eab4a09d251a76d0043e018172db324a23fcdac70f77a551c11f618/platformdirs-4.1.0-py3-none-any.whl.metadata
  Downloading platformdirs-4.1.0-py3-none-any.whl.metadata (11 kB)
Downloading pipenv-2023.11.17-py3-none-any.whl (3.2 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.2/3.2 MB 6.1 MB/s eta 0:00:00
Downloading virtualenv-20.25.0-py3-none-any.whl (3.8 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.8/3.8 MB 8.7 MB/s eta 0:00:00
Downloading certifi-2023.11.17-py3-none-any.whl (162 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 162.5/162.5 kB 6.6 MB/s eta 0:00:00
Downloading distlib-0.3.8-py2.py3-none-any.whl (468 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 468.9/468.9 kB 10.5 MB/s eta 0:00:00
Downloading filelock-3.13.1-py3-none-any.whl (11 kB)
Downloading platformdirs-4.1.0-py3-none-any.whl (17 kB)
Installing collected packages: distlib, platformdirs, filelock, certifi, virtualenv, pipenv
Successfully installed certifi-2023.11.17 distlib-0.3.8 filelock-3.13.1 pipenv-2023.11.17 platformdirs-4.1.0 virtualenv-20.25.0
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

[notice] A new release of pip is available: 23.2.1 -> 23.3.2
[notice] To update, run: pip install --upgrade pip

pipのアップグレード

ほぼ必ずと言っていいほどpipをアップグレードするように言われるので、pipをアップグレードします。

pip install --upgrade pip

出力結果

Requirement already satisfied: pip in /usr/local/lib/python3.12/site-packages (23.2.1)
Collecting pip
  Obtaining dependency information for pip from https://files.pythonhosted.org/packages/15/aa/3f4c7bcee2057a76562a5b33ecbd199be08cdb4443a02e26bd2c3cf6fc39/pip-23.3.2-py3-none-any.whl.metadata
  Downloading pip-23.3.2-py3-none-any.whl.metadata (3.5 kB)
Downloading pip-23.3.2-py3-none-any.whl (2.1 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 6.5 MB/s eta 0:00:00
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 23.2.1
    Uninstalling pip-23.2.1:
      Successfully uninstalled pip-23.2.1
Successfully installed pip-23.3.2
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv

Pipenvの使い方

バージョン確認

コマンド

pipenv --version

出力結果

pipenv, version 2023.12.0

ヘルプ

pipenvコマンドのオプションがわからなくなったら有用です。

コマンド

pipenv --help

出力結果

Usage: pipenv [OPTIONS] COMMAND [ARGS]...

Options:
  --where                         Output project home information.
  --venv                          Output virtualenv information.
  --py                            Output Python interpreter information.
  --envs                          Output Environment Variable options.
  --rm                            Remove the virtualenv.
  --bare                          Minimal output.
  --man                           Display manpage.
  --support                       Output diagnostic information for use in
                                  GitHub issues.
  --site-packages / --no-site-packages
                                  Enable site-packages for the virtualenv.
                                  [env var: PIPENV_SITE_PACKAGES]
  --python TEXT                   Specify which version of Python virtualenv
                                  should use.
  --clear                         Clears caches (pipenv, pip).  [env var:
                                  PIPENV_CLEAR]
  -q, --quiet                     Quiet mode.
  -v, --verbose                   Verbose mode.
  --pypi-mirror TEXT              Specify a PyPI mirror.
  --version                       Show the version and exit.
  -h, --help                      Show this message and exit.


Usage Examples:
   Create a new project using Python 3.7, specifically:
   $ pipenv --python 3.7

   Remove project virtualenv (inferred from current directory):
   $ pipenv --rm

   Install all dependencies for a project (including dev):
   $ pipenv install --dev

   Create a lockfile containing pre-releases:
   $ pipenv lock --pre

   Show a graph of your installed dependencies:
   $ pipenv graph

   Check your installed dependencies for security vulnerabilities:
   $ pipenv check

   Install a local setup.py into your virtual environment/Pipfile:
   $ pipenv install -e .

   Use a lower-level pip command:
   $ pipenv run pip freeze

Commands:
  check         Checks for PyUp Safety security vulnerabilities and against
                PEP 508 markers provided in Pipfile.
  clean         Uninstalls all packages not specified in Pipfile.lock.
  graph         Displays currently-installed dependency graph information.
  install       Installs provided packages and adds them to Pipfile, or (if no
                packages are given), installs all packages from Pipfile.
  lock          Generates Pipfile.lock.
  open          View a given module in your editor.
  requirements  Generate a requirements.txt from Pipfile.lock.
  run           Spawns a command installed into the virtualenv.
  scripts       Lists scripts in current environment config.
  shell         Spawns a shell within the virtualenv.
  sync          Installs all packages specified in Pipfile.lock.
  uninstall     Uninstalls a provided package and removes it from Pipfile.
  update        Runs lock, then sync.
  upgrade       Resolves provided packages and adds them to Pipfile, or (if no
                packages are given), merges results to Pipfile.lock
  verify        Verify the hash in Pipfile.lock is up-to-date.

Pythonバージョンの固定

プロジェクトが始まったらPythonのバージョンを固定してしまいましょう。意図しないアップデートによりアプリが動作しなくなることを防ぎます。特にDockerfileなどでpython:latestなどのイメージが指定されている場合最新のバージョンにアップデートされてしまうので注意が必要です。ここではDockerfileの話とは違いますが、Dockerfile側のFROM句のバージョンもpython:3.12に合わせておくことをお勧めします。

コマンド

pipenv --python 3.12

出力結果

3.12
3.12
Creating a virtualenv for this project...
Pipfile: /app/Pipfile
Using /usr/local/bin/python (3.12.1) to create virtualenv...
⠋ Creating virtual environment...created virtual environment CPython3.12.1.final.0-64 in 73ms
  creator CPython3Posix(dest=/root/.local/share/virtualenvs/app-4PlAip0Q, clear=False, no_vcs_ignore=False, global=False)
  seeder FromAppData(download=False, pip=bundle, via=copy, app_data_dir=/root/.local/share/virtualenv)
    added seed packages: pip==23.3.1
  activators BashActivator,CShellActivator,FishActivator,NushellActivator,PowerShellActivator,PythonActivator

✔ Successfully created virtual environment!
Virtualenv location: /root/.local/share/virtualenvs/app-4PlAip0Q
Creating a Pipfile for this project...

パッケージインストール

新たにパッケージをインストールする場合は、pipenv installコマンドを使用します。間違えてpipコマンドを使わないようにしましょう。pipでインストールするとシステムにインストールされてしまい、この場合だとDockerコンテナ本体にインストールされてしまいます。

コマンド

Webアクセスに使うrequestsパッケージをインストールします。

pipenv install requests

出力結果

Installing requests...
Resolving requests...
Added requests to Pipfile's [packages] ...
✔ Installation Succeeded
Pipfile.lock not found, creating...
Locking [packages] dependencies...
Building requirements...
Resolving dependencies...
✔ Success!
Locking [dev-packages] dependencies...
Updated Pipfile.lock (6d409d9dcc191f009669dbea1693dfcd9b075ba07ec8803a319f31229271e662)!
Installing dependencies from Pipfile.lock (71e662)...
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

Pipenv経由でのコマンド実行

コマンド

例として先ほどインストールしたrequestsパッケージを使用して、https://www.google.comにアクセスし、HTTPステータスコードを確認します。

pipenv run python -c 'import requests; print(requests.get("https://www.google.com").status_code)'

出力結果

200 OKが返ってきました。

200

パッケージアンインストール

コマンド

requestsパッケージをアンインストールします。

pipenv uninstall requests

出力結果

Removing requests from Pipfile.lock...
Removed requests from Pipfile category packages
Uninstalling requests...
Found existing installation: requests 2.31.0
Uninstalling requests-2.31.0:
  Successfully uninstalled requests-2.31.0

Locking [packages] dependencies...
Locking [dev-packages] dependencies...
Updated Pipfile.lock (bf734de02c88a9a850242d060bf203f3153ae3dc94dd18feccc5733d0edef22f)!

パッケージバージョン指定

先ほどのrequestsはバージョン指定をしなかったので最新バージョンの2.30.1がインストールされました。バージョンを2.30.0に指定してインストール方法は~=でバージョンを指定します。==でもいいみたいですが~=が推奨されているようです。

コマンド

pipenv install requests~=2.30.0

出力結果

Installing requests~=2.30.0...
Resolving requests~=2.30.0...
Added requests to Pipfile's [packages] ...
✔ Installation Succeeded
Pipfile.lock (def22f) out of date, updating to (d68c16)...
Locking [packages] dependencies...
Building requirements...
Resolving dependencies...
✔ Success!
Locking [dev-packages] dependencies...
Updated Pipfile.lock (568f3e950e7dec604402593cb1b6ecc1c05372f809654c7ea2b71ed816d68c16)!
Installing dependencies from Pipfile.lock (d68c16)...
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

開発環境でのみ使うパッケージのインストール

例えばpytestなどのテストフレームワークは、本番環境にインストールする必要がありません。開発環境のみに必要なパッケージです。開発環境のみにインストールするには–devオプションを指定してインストールします。

コマンド

pipenv install pytest --dev

出力結果

出力結果を見るとdev-packagesにインストールされていることがわかります。

Installing pytest...
Resolving pytest...
Added pytest to Pipfile's [dev-packages] ...
✔ Installation Succeeded
Pipfile.lock (d68c16) out of date, updating to (7a901d)...
Locking [packages] dependencies...
Building requirements...
Resolving dependencies...
✔ Success!
Locking [dev-packages] dependencies...
Building requirements...
Resolving dependencies...
✔ Success!
Updated Pipfile.lock (7bde5a89027201bfadc898f25c1f1def01983c8a411e3eaabaf60cb8297a901d)!
Installing dependencies from Pipfile.lock (7a901d)...
Installing dependencies from Pipfile.lock (7a901d)...
To activate this project's virtualenv, run pipenv shell.
Alternatively, run a command inside the virtualenv with pipenv run.

バージョン管理のコツ

これまでPythonのDockerコンテナ上でpipenvのコマンドを実行してきました。ここでexitコマンドでDockerコンテナを抜けると、カレントディレクトリにPipfilePipfile.lockファイルが作成されています。これらPipfilePipfile.lockをバージョン管理化に置いてください。他の開発メンバーは、このファイルを頼りにpipenv installすれば、同じバージョンでPythonパッケージをインストールすることができます。

参考

Pipenv: 人間のためのPython開発ワークフロー — pipenv 2018.11.27.dev0 ドキュメント

コメント

タイトルとURLをコピーしました