Pipenvの基本的な使い方

https://farm4.staticflickr.com/3931/33173826122_b7ee8f1a26_k_d.jpg

このドキュメントではPipenvのより基本的な機能を対象としています。

☤ PipfileとPipfile.lockの例

Pipfiles contain information for the dependencies of the project, and supersedes the requirements.txt file used in most Python projects. You should add a Pipfile in the Git repository letting users who clone the repository know the only thing required would be installing Pipenv in the machine and typing pipenv install. Pipenv is a reference implementation for using Pipfile.

Pipfile とそこから生成された Pipfile.lock の簡単な例を示します。

Pipfileの例

[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true
name = "pypi"

[packages]
requests = "*"


[dev-packages]
pytest = "*"

Pipfile.lockの例

{
    "_meta": {
        "hash": {
            "sha256": "8d14434df45e0ef884d6c3f6e8048ba72335637a8631cc44792f52fd20b6f97a"
        },
        "host-environment-markers": {
            "implementation_name": "cpython",
            "implementation_version": "3.6.1",
            "os_name": "posix",
            "platform_machine": "x86_64",
            "platform_python_implementation": "CPython",
            "platform_release": "16.7.0",
            "platform_system": "Darwin",
            "platform_version": "Darwin Kernel Version 16.7.0: Thu Jun 15 17:36:27 PDT 2017; root:xnu-3789.70.16~2/RELEASE_X86_64",
            "python_full_version": "3.6.1",
            "python_version": "3.6",
            "sys_platform": "darwin"
        },
        "pipfile-spec": 5,
        "requires": {},
        "sources": [
            {
                "name": "pypi",
                "url": "https://pypi.python.org/simple",
                "verify_ssl": true
            }
        ]
    },
    "default": {
        "certifi": {
            "hashes": [
                "sha256:54a07c09c586b0e4c619f02a5e94e36619da8e2b053e20f594348c0611803704",
                "sha256:40523d2efb60523e113b44602298f0960e900388cf3bb6043f645cf57ea9e3f5"
            ],
            "version": "==2017.7.27.1"
        },
        "chardet": {
            "hashes": [
                "sha256:fc323ffcaeaed0e0a02bf4d117757b98aed530d9ed4531e3e15460124c106691",
                "sha256:84ab92ed1c4d4f16916e05906b6b75a6c0fb5db821cc65e70cbd64a3e2a5eaae"
            ],
            "version": "==3.0.4"
        },
        "idna": {
            "hashes": [
                "sha256:8c7309c718f94b3a625cb648ace320157ad16ff131ae0af362c9f21b80ef6ec4",
                "sha256:2c6a5de3089009e3da7c5dde64a141dbc8551d5b7f6cf4ed7c2568d0cc520a8f"
            ],
            "version": "==2.6"
        },
        "requests": {
            "hashes": [
                "sha256:6a1b267aa90cac58ac3a765d067950e7dbbf75b1da07e895d1f594193a40a38b",
                "sha256:9c443e7324ba5b85070c4a818ade28bfabedf16ea10206da1132edaa6dda237e"
            ],
            "version": "==2.18.4"
        },
        "urllib3": {
            "hashes": [
                "sha256:06330f386d6e4b195fbfc736b297f58c5a892e4440e54d294d7004e3a9bbea1b",
                "sha256:cc44da8e1145637334317feebd728bd869a35285b93cbb4cca2577da7e62db4f"
            ],
            "version": "==1.22"
        }
    },
    "develop": {
        "py": {
            "hashes": [
                "sha256:2ccb79b01769d99115aa600d7eed99f524bf752bba8f041dc1c184853514655a",
                "sha256:0f2d585d22050e90c7d293b6451c83db097df77871974d90efd5a30dc12fcde3"
            ],
            "version": "==1.4.34"
        },
        "pytest": {
            "hashes": [
                "sha256:b84f554f8ddc23add65c411bf112b2d88e2489fd45f753b1cae5936358bdf314",
                "sha256:f46e49e0340a532764991c498244a60e3a37d7424a532b3ff1a6a7653f1a403a"
            ],
            "version": "==3.2.2"
        }
    }
}

☤ 一般的なオススメの方法とバージョン管理

  • 一般的には、 PipfilePipfile.lock の両方をバージョン管理してください。
  • 複数バージョンのPythonを対象とする場合は、 Pipfile.lock はバージョン管理に含めないでください。
  • Specify your target Python version in your Pipfile's [requires] section. Ideally, you should only have one target Python version, as this is a deployment tool. python_version should be in the format X.Y and python_full_version should be in X.Y.Z format.
  • pipenv installpip install の文法と完全な互換性があります。 pip install の文法については ここ に完全なドキュメントがあります。
  • Note that the Pipfile uses the TOML Spec.

☤ Pipenvのワークフローの例

プロジェクトのレポジトリをクローンまたは作成する:

$ cd myproject

Pipfileがあった場合には、Pipfileの内容でインストールする:

$ pipenv install

もしくは、新しいプロジェクトにパッケージを追加する:

$ pipenv install <package>

このコマンドは Pipfile が無ければ作成します。 既に存在していた場合は、引数で与えたパッケージが追加されるよう自動的に Pipfile を編集します。

次に、Pipenvシェルを有効化する:

$ pipenv shell
$ python --version

このコマンドは新しいシェルのサブプロセスを立ち上げます。このプロセスは exit を使って停止できます。

☤ Pipenvのアップグレードの流れの例

  • どれに変更があったかをコマンド $ pipenv update --outdated で調べます。
  • パッケージを更新します。方法は2つあります:
    1. 全部のパッケージを更新したい? それなら $ pipenv update とするだけです。
    2. 一度に1つだけパッケージを更新したい? パッケージごとに $ pipenv update <pkg> とします。

☤ requirements.txtからのインポート

pipenv install を実行したときに requirements.txt ファイルしか無い場合は、Pipenvは自動でそのファイルの内容をインポートし Pipfile を作成します。

requirementsファイルをインポートするのに、 $ pipenv install -r path/to/requirements.txt と指定することもできます。

requirementsファイルでバージョン番号が固定されている場合は、新しく作成された Pipfile を編集して固定バージョンを取り除いた上で、 pipenv コマンドでは固定バージョンのままにしておきたいでしょう。 とりあえず今のところは固定バージョンを Pipfile.lock に保持しておきたい場合は、 pipenv lock --keep-outdated を実行してください。 すぐに アップグレード するのも忘れずに!

☤ パッケージのバージョンを指定する

Semantic Versioning scheme (すなわち major.minor.micro)を使用して、パッケージのバージョンを指定できます。

例えば、インストールリクエストで次の記法が使えます:

$ pipenv install requests~=1.2

Pipenvはバージョン 1.2 やそのマイナーアップデートをインストールしますが、2.0 はインストールしません。

このコマンドを実行することで、バージョン指定を反映するように Pipfile が自動で更新されます。

一般的には、Pipenvはpipと同じバージョン指定形式を使います。 しかし、 PEP 440 によると、ハイフンやプラス記号を含んだバージョン名は使えないことに注意してください。

境界を含む、あるいは含まないバージョン比較をするには、次の記法が使えます:

$ pipenv install "requests>=1.4"   # will install a version equal or larger than 1.4.0
$ pipenv install "requests<=2.13"  # will install a version equal or lower than 2.13.0
$ pipenv install "requests>2.19"   # will install 2.19.1 but not 2.19.0

注釈

The use of double quotes around the package and version specification (i.e. "requests>2.19") is highly recommended to avoid issues with Input and output redirection in Unix-based operating systems.

The use of ~= is preferred over the == identifier as the latter prevents pipenv from updating the packages:

$ pipenv install "requests~=2.2"  # locks the major version of the package (this is equivalent to using ==2.*)

特定のバージョンのインストールを防ぐには != 識別子が使えます。

有効な識別子とより複雑な使用場面の深い説明は the relevant section of PEP-440 を確認してください。

☤ Pythonのバージョンを指定する

インストール済みの (そして PATH 上にある) 特定のバージョンのPythonを使って、新しく仮想環境を作るには、 --python VERSION フラグを次のように使います:

Python 3を使うには:

$ pipenv --python 3

Python 3.6を使うには:

$ pipenv --python 3.6

Python 2.7.14を使うには:

$ pipenv --python 2.7.14

このようにPythonのバージョンが与えられたときは、Pipenvはそのバージョンに合うPythonをシステムから自動で探しに行きます。

Pipfile がまだ作成されていなかった場合は、次のような内容で作成されます:

[[source]]
url = "https://pypi.python.org/simple"
verify_ssl = true

[dev-packages]

[packages]

[requires]
python_version = "3.6"

注釈

[requires] python_version = "3.6" という文言が含まれていると、アプリケーションがこのバージョンのPythonを要求していることを示し、将来 (例えば他のマシンで) この Pipfile に対して pipenv install を実行するときに自動で使われます。 この指定が間違っている場合は、気にせずこのセクションを削除してください。

コマンドラインでも [requires] でもPythonのバージョンを指定しなかった場合は、 python_full_versionpython_version は自動で選ばれ、システムのデフォルトとしてインストールされている python が実行時に選ばれます。

☤ 編集可能な依存関係 (例えば -e . )

Pipenvに編集可能なパスとしてインストールするよう指示できます — この機能は、パッケージの開発作業をしているときに、現在の作業ディレクトリを指すのに便利なことが多いです:

$ pipenv install --dev -e .

$ cat Pipfile
...
[dev-packages]
"e1839a8" = {path = ".", editable = true}
...

注釈

全ての子依存関係も Pipfile.lock に追加されます。 -e オプションを設定しないでおくと、子依存関係は Pipfile.lock には追加され ません

☤ Pipenvによる環境管理

Pipenvの環境管理で使うであろう主要な3つのコマンドは $ pipenv install$ pipenv uninstall$ pipenv lock です。

$ pipenv install

$ pipenv install は、Pipenvの仮想環境にパッケージをインストールしたり、Pipfileを更新したりするのに使います。

次の形式の基本的なインストールコマンドと一緒に:

$ pipenv install [package names]

ユーザーは以下の追加のパラメータを渡せます:

  • --two — システムのシンボリックリンク python2 を使い、仮想環境へのインストールを行います。
  • --three — システムのシンボリックリンク python3 を使い、仮想環境へのインストールを行います。
  • --python — 引数で与えられたPythonインタプリタを使い、仮想環境へのインストールを行います。

警告

上のコマンドは一緒に使ってはいけません。 これらのコマンドは 破壊的 であり、現在の仮想環境を削除してから、適切なバージョンが使われた仮想環境に置き換えられます。

注釈

Pipenvで作成された仮想環境は、予想したものと異なっているかもしれません。 危険な文字 (つまり、空白、ラインフィード、キャリッジリターン、タブだけでなく $`!*@" も) はアンダースコアに変換されます。 さらに、現在のフォルダのフルパスは "スラッグ値" にエンコードされ、仮想環境名が一意になるように末尾に追加されます。

  • --devPipfiledevelop パッケージと default パッケージの両方をインストールします。
  • --system — 仮想環境ではなく、システムの pip コマンドを使用します。
  • --deploy — Make sure the packages are properly locked in Pipfile.lock, and abort if the lock file is out-of-date.
  • --ignore-pipfilePipfile を無視し、 Pipfile.lock を使ってインストールします。
  • --skip-lockPipfile.lock を無視し、 Pipfile を使ってインストールします。 それに加えて、 Pipfile の変更部分を Pipfile.lock へは反映しません。

$ pipenv uninstall

$ pipenv uninstallpipenv install の全てのパラメータに加えて、 --all--all-dev もサポートしています。

  • --all — このパラメータを付けると、仮想環境から全てのファイルを除去しますが、Pipfileだけは触らずに残します。
  • --all-dev — このパラメータを付けると、開発環境の全てのパッケージを仮想環境から除去し、Pipfileからも削除します。

$ pipenv lock

$ pipenv lockPipfile.lock を作成するために使用します。 このファイルにはプロジェクトの 全ての 依存パッケージ (とさらにその依存パッケージ) と、それらの利用可能な最新のバージョン、ダウンロード済みのファイルの現在のハッシュが宣言されています。 このファイルのおかげで、繰り返し可能かつ、最も重要な機能である 決定論的な ビルドが保証されています。

☤ シェルの設定について

シェルはたいていサブシェルを使うのに間違った設定になっていることがあるので、 $ pipenv shell --fancy は予期せぬ状態を引き起こすかもしれません。 その場合は、 $ pipenv shell を試してみてください。 これは "互換モード" を使っていて、間違った設定がされていてもサブシェルを起動しようと試みます。

適切なシェル設定では、(たいていはこの設定になっていますが) 全てのサブシェルが起動している間ではなく、あるログインセッションが起動している間だけ PATH のような環境変数を設定します。 fishでは、適切な設定は次のようになります:

if status --is-login
    set -gx PATH /usr/local/bin $PATH
end

各自のシェルに対して、 ~/.profile~/.bashrc などの適切なファイルで同様の設定をしてください。

注釈

シェルは対話モードで起動します。 つまり、シェルが対話モード用の設定をあるファイルから読み込む (例えば、bashはデフォルトで対話モード用の設定ファイル ~/.bashrc を探しに行きます) 場合は、その設定ファイルを編集 (もしくは作成) する必要があります。

$ pipenv shell の問題に遭遇した場合は、まずは PIPENV_SHELL 環境変数を確認してください。$ pipenv shell は使用可能な場合に、この環境変数を利用します。 詳しくは、☤ 環境変数による設定 を参照してください。

☤ バージョン管理システムについての但し書き

pipenvは、gitやその他のバージョン管理システムで次の規則に従った形式のURLを使っているものからパッケージをインストールできます。

<vcs_type>+<scheme>://<location>/<user_or_organization>/<repository>@<branch_or_tag>#egg=<package_name>

The only optional section is the @<branch_or_tag> section. When using git over SSH, you may use the shorthand vcs and scheme alias git+git@<location>:<user_or_organization>/<repository>@<branch_or_tag>#<package_name>. Note that this is translated to git+ssh://git@<location> when parsed.

Note that it is strongly recommended that you install any version-controlled dependencies in editable mode, using pipenv install -e, in order to ensure that dependency resolution can be performed with an up to date copy of the repository each time it is performed, and that it includes all known dependencies.

Below is an example usage which installs the git repository located at https://github.com/requests/requests.git from tag v2.20.1 as package name requests:

$ pipenv install -e git+https://github.com/requests/requests.git@v2.20.1#egg=requests
Creating a Pipfile for this project...
Installing -e git+https://github.com/requests/requests.git@v2.20.1#egg=requests...
[...snipped...]
Adding -e git+https://github.com/requests/requests.git@v2.20.1#egg=requests to Pipfile's [packages]...
[...]

$ cat Pipfile
[packages]
requests = {git = "https://github.com/requests/requests.git", editable = true, ref = "v2.20.1"}

Valid values for <vcs_type> include git, bzr, svn, and hg. Valid values for <scheme> include http, https, ssh, and file. In specific cases you also have access to other schemes: svn may be combined with svn as a scheme, and bzr can be combined with sftp and lp.

You can read more about pip's implementation of VCS support here. For more information about other options available when specifying VCS dependencies, please check the Pipfile spec.

☤ セキュリティ機能 Pipfile.lock

Pipfile.lockpip に新しく入った偉大なセキュリティ上の改善を利用します。 デフォルトでは、 Pipfile.lock はダウンロードされたパッケージごとのsha256ハッシュから生成されます。 これにより pip は、ネットワークが驚異に晒されていたり、信頼できないPyPIエンドポイントから依存パッケージをインストールしたりしているときに、意図したとおりのパッケージをインストールしていることを保証できます。

開発環境から本番環境へプロジェクトを昇格させる方法でデプロイに取り組むことを強く推奨します。 pipenv lock を使って開発環境の依存関係をコンパイルし、そのコンパイルされた Pipfile.lock を全ての本番環境にデプロイして再現可能なビルドができます。

注釈

If you'd like a requirements.txt output of the lockfile, run $ pipenv lock -r. This will include all hashes, however (which is great!). To get a requirements.txt without hashes, use $ pipenv run pip freeze.