Pipenv: 人間のためのPython開発ワークフロー

https://img.shields.io/pypi/v/pipenv.svg https://img.shields.io/pypi/l/pipenv.svg https://img.shields.io/pypi/pyversions/pipenv.svg

Pipenv は、全てのパッケージングの世界 (bundler、composer、npm、cargo、yarnなどなど。) における最高のものをPythonの世界にもたらすことを目的としたツールです。 我々の世界ではWindowsは第一級市民です。

Pipenvは、手動でパッケージのインストールおよびアンインストールを行うのと同じように Pipfile に対してパッケージの追加および削除を行うのに加え、自動でプロジェクト用の仮想環境を作成し管理します。 またPipenvは、いかなるときも重要な Pipfile.lock を生成し、これを利用しビルドが常に同じ結果になるようにします。

Pipenvは主にアプリケーションのユーザーと開発者に、簡単に作業環境を作れる方法を提供するためのツールです。 ライブラリとアプリケーションの違いや、依存関係を定義するための setup.pyPipfile の使い方の違いについては、 ☤ Pipfile vs setup.py を参照してください。

a short animation of pipenv at work

Pipenvは様々な側面を持つ問題を解決しようとしています:

  • もう pipvirtualenv を別々に使う必要はありません。 両者は連係して動作します。
  • requirements.txt ファイルの管理は 問題になり得る ので、代わりにPipenvは Pipfile および Pipfile.lock を使い、最小限の依存関係の宣言と直前にテストした依存関係の組み合わせを区別します。
  • ハッシュがどこでもいつでも使われます。 安心安全。 そして、自動でセキュリティの脆弱性を白日の下に晒します。
  • 依存パッケージの最新バージョンを使うことで 古いコンポーネントが引き起こす セキュリティリスクを最小化することを強くお薦めします。
  • 依存関係グラフを深く理解できるようになります (例えば $ pipenv graph)。
  • .env ファイルを読み込むことで、開発ワークフローの能率を上げます。

You can quickly play with Pipenv right in your browser:

Try in browser

さぁ今すぐこれからPipenvをインストール!

If you're on MacOS, you can install Pipenv easily with Homebrew. You can also use Linuxbrew on Linux using the same command:

$ brew install pipenv

あるいは、Fedora 28を使っている場合には次のようにします:

$ sudo dnf install pipenv

それ以外の場合は、 ☤ Pipenvのインストール の章の手順を参照してください。

✨🍰✨

Pipenvと仮想環境

https://farm3.staticflickr.com/2943/33485660921_dfc0494739_k_d.jpg

このチュートリアルでは、Pythonのパッケージをインストールして使う体験をしてもらいます。

このチュートリアルは必要とするツールをインストールして使う方法を解説し、ベストプラクティスを強く推奨するものです。 Pythonは非常に多岐に渡る目的に使われていて、依存関係をどのように管理したいかは厳密には、どのようにソフトウェアの公開を決めるかによって変わるかもしれないことを心に留めておいてください。 このガイダンスを直接適用するのに一番向いているのは、(Webアプリケーションを含む) ネットワークサービスの開発とデプロイですが、どんな種類のプロジェクトの開発環境やテスト環境の管理にも非常によく適したものになっています。

注釈

このガイドはPython 3向けに書かれていますが、とある理由でまだPython 2.7を使っている場合でも、それぞれの指示はきちんと動くでしょう。

☤ Pythonとpipがあるかの確認

先に進む前に、Pythonがインストールしてあって、コマンドラインから使えることを確認してください。 次のコマンドを実行して確認できます:

$ python --version

3.6.2 のような表示が出力されたと思います。 もしPythonをインストールしていなかったら、 python.org から最新のバージョン3.xをインストールするか、 The Hitchhiker's Guide to PythonInstalling Python 節を参照してください。

注釈

もしあなたが初心者で次のようなエラーが出てしまったら:

>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined

このエラーが起きたのは、 python コマンドは シェル (ターミナルコンソール とも呼ばれます) で動かすものだからです。 Python for Beginnersというサイトの getting started tutorial を参照し、OSのシェルの使い方やPythonとやり取りする入門をしてください。

さらに、pipが使える状態にあるかを確認する必要があります。 次のコマンドを実行して確認できます:

$ pip --version
pip 9.0.1

ソースコードや python.org のインストーラーや HomebrewLinuxbrew からPythonをインストールした場合は、既にpipがインストールされているはずです。 Linuxを使っていて、OSのパッケージマネージャーを使ってインストールした場合には、それとは別に pipのインストール をしなければならないかもしれません。

HomebrewまたはLinuxbrewを使ってPipenvをインストールするつもりの場合は、この手順はスキップできます。 HomebrewあるいはLinuxbrewのインストーラはpipの面倒も見てくれます。

☤ Pipenvのインストール

PipenvはPythonプロジェクトのための依存関係管理ツールです。 もしNode.jsの npm やRubyの bundler に馴染みがあるなら、Pipenvはそれらのツールとやりたいことはよく似ています。 pipはPythonのパッケージをインストールできますが、Pipenvは通常のユースケースでの依存関係管理を簡単にするより高度なツールとして推奨されています。

☤ HomebrewでのPipenvのインストール方法

Homebrew はmacOSの人気のあるオープンソースパッケージマネージシステムです。 Linuxユーザーのために、Homebrewを移植したのが Linuxbrew です。

HomebrewやLinuxbrewでpipenvをインストールするとpipenvとその依存パッケージを隔離された仮想環境に閉じ込めるので、他のインストールされているPythonに影響は与えません。

HomebrewあるいはLinuxbrewがインストールできたら次のコマンドを実行します:

$ brew install pipenv

いつでもPipenvをアップグレードするには次のコマンドを実行します:

$ brew upgrade pipenv
☤ pipenvの実用的なインストール方法

もしインストールされた今も使っているpipがあって、ある "ツール群" タイプのPythonモジュールをどの環境でも使うユーティリティとしてメンテナンスしている場合は、pip の ユーザーインストール を使うとホームディレクトリにインストールできます。 依存関係どうしの影響の関係で、この方法でインストールするツールは、virtualenv、Pipenv、toxのようなPythonを使う作業の工程のための基本要素となるソフトウェアだけに制限すべきという点に注意してください。

次のコマンドでインストールします:

$ pip install --user pipenv

注釈

このコマンドは user installation を行い、システム全体に関わるパッケージを壊さないようにします。 インストールを行った後に pipenv が使えるようにならない場合は、 user base のバイナリディレクトリを PATH に追加する必要があります。

LinuxとmacOSでは python -m site --user-base を実行してユーザーのベースバイナリディレクトリを見付け、その末尾に bin を追加します。 例えば、このコマンドはたいてい ~/.local (~ はあなたのホームディレクトリの絶対パスへ展開されたもの) なので、 ~/.local/binPATH に追加する必要があります。 ~/.profile を修正 すると PATH に行った設定が再起動しても消えません。

Windows では python -m site --user-site を実行してユーザーのベースバイナリディレクトリを見付け、 site-packagesScripts で置き換えます。 例えば、このコマンドは C:\Users\Username\AppData\Roaming\Python36\site-packages のようなパスを返すので、 C:\Users\Username\AppData\Roaming\Python36\ScriptsPATH に含める必要があります。 コントロールパネル でユーザー環境変数の PATH に設定すると再起動しても消えません。 PATH の変更を有効にするには一度ログアウトする必要があるかもしれません。

さらに詳しいことは ユーザーインストールの説明 を参照してください。

いつでもPipenvをアップグレードするには次のコマンドを実行します:

$ pip install --user --upgrade pipenv
☤ 大雑把なPipenvのインストール方法

もしpipをまだインストールしていなくても、この大雑把なインストール方法を使って、Pipenvのシステム全体を立ち上げられます:

$ curl https://raw.githubusercontent.com/pypa/pipenv/master/get-pipenv.py | python

☤ プロジェクトで使うパッケージのインストール

Pipenvはプロジェクトごとに依存関係を管理します。 パッケージをインストールするには、プロジェクトのディレクトリ (もしくは、このチュートリアル用の空ディレクトリ) に移動して、次のコマンドを実行してください:

$ cd myproject
$ pipenv install requests

Pipenvは非常に優れた Requests ライブラリをインストールし、プロジェクトディレクトリに Pipfile を作成します。 Pipfileは、プロジェクトを他の人に共有するときのように、依存関係を再インストールする必要が出てきたときに、プロジェクトがどの依存関係を必要としているのかを追跡するのに使います。 これに似た出力が表示されるはずです (もっとも、表示されている正確なパスは異なるでしょう):

Creating a Pipfile for this project...
Creating a virtualenv for this project...
Using base prefix '/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6'
New python executable in ~/.local/share/virtualenvs/tmp-agwWamBd/bin/python3.6
Also creating executable in ~/.local/share/virtualenvs/tmp-agwWamBd/bin/python
Installing setuptools, pip, wheel...done.

Virtualenv location: ~/.local/share/virtualenvs/tmp-agwWamBd
Installing requests...
Collecting requests
  Using cached requests-2.18.4-py2.py3-none-any.whl
Collecting idna<2.7,>=2.5 (from requests)
  Using cached idna-2.6-py2.py3-none-any.whl
Collecting urllib3<1.23,>=1.21.1 (from requests)
  Using cached urllib3-1.22-py2.py3-none-any.whl
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Using cached chardet-3.0.4-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests)
  Using cached certifi-2017.7.27.1-py2.py3-none-any.whl
Installing collected packages: idna, urllib3, chardet, certifi, requests
Successfully installed certifi-2017.7.27.1 chardet-3.0.4 idna-2.6 requests-2.18.4 urllib3-1.22

Adding requests to Pipfile's [packages]...
P.S. You have excellent taste! ✨ 🍰 ✨

☤ インストールされたパッケージを使う

これでRequestsがインストールされたので、単純な main.py ファイルを作成し、Requestsを使えます:

import requests

response = requests.get('https://httpbin.org/ip')

print('Your IP is {0}'.format(response.json()['origin']))

そして pipenv run を使って、このスクリプトが実行できます:

$ pipenv run python main.py

これに似た出力が表示されるはずです:

Your IP is 8.8.8.8

$ pipenv run を使うと、インストールしたパッケージがスクリプトから使えることが保証されます。 インストールしたパッケージに全てのコマンドがアクセスできることが保証された新しいシェルの起動もできます。

☤ 仮想環境の対応付けについての注意書き

  • Pipenvは自動的にプロジェクトをそれ専用の仮想環境に対応付けます。
  • 仮想環境は、プロジェクトのルートディレクトリにそのパスのハッシュを付け足した名前(例えば、 my_project-a3de50)で共通の場所に保存されます。
  • プロジェクトのパスを変更した場合は、そのデフォルトの対応付けは壊れてしまい、Pipenvはプロジェクトの仮想環境を見付けることも、使用することもできなくなります。
  • 後でパスを変更して起きる問題を避けるために、.bashrcか.zshrc(あるいは他のシェル設定ファイル)に export PIPENV_VENV_IN_PROJECT=1 を設定して、プロジェクトのディレクトリ内に仮想環境を作るようにするのも良いでしょう。

☤ 次のステップ

おめでとうございます、Pythonのパッケージをインストールして使う方法が学べました! ✨ 🍰 ✨

リリースとバージョンヒストリー

2018.11.26 (2018-11-26)

バグ修正
  • POSIXでスクリプトを走らせる前に、環境変数が正しく展開されるようになりました。 #3178
  • Pipenv will no longer disable user-mode installation when the --system flag is passed in. #3222
  • Fixed an issue with attempting to render unicode output in non-unicode locales. #3223
  • Fixed a bug which could cause failures to occur when parsing python entries from global pyenv version files. #3224
  • Fixed an issue which prevented the parsing of named extras sections from certain setup.py files. #3230
  • Correctly detect the virtualenv location inside an activated virtualenv. #3231
  • Fixed a bug which caused spinner frames to be written to stdout during locking operations which could cause redirection pipes to fail. #3239
  • Fixed a bug that editable pacakges can't be uninstalled correctly. #3240
  • Corrected an issue with installation timeouts which caused dependency resolution to fail for longer duration resolution steps. #3244
  • Adding normal pep 508 compatible markers is now fully functional when using VCS dependencies. #3249
  • Updated requirementslib and pythonfinder for multiple bugfixes. #3254
  • Pipenv will now ignore hashes when installing with --skip-lock. #3255
  • Fixed an issue where pipenv could crash when multiple pipenv processes attempted to create the same directory. #3257
  • Fixed an issue which sometimes prevented successful creation of project pipfiles. #3260
  • pipenv install will now unset the PYTHONHOME environment variable when not combined with --system. #3261
  • Pipenv will ensure that warnings do not interfere with the resolution process by suppressing warnings' usage of standard output and writing to standard error instead. #3273
  • Fixed an issue which prevented variables from the environment, such as PIPENV_DEV or PIPENV_SYSTEM, from being parsed and implemented correctly. #3278
  • Clear pythonfinder cache after Python install. #3287
  • Fixed a race condition in hash resolution for dependencies for certain dependencies with missing cache entries or fresh Pipenv installs. #3289
  • Pipenv will now respect top-level pins over VCS dependency locks. #3296
Vendored Libraries
  • Update vendored dependencies to resolve resolution output parsing and python finding:
    • pythonfinder 1.1.9 -> 1.1.10
    • requirementslib 1.3.1 -> 1.3.3
    • vistir 0.2.3 -> 0.2.5 #3280

2018.11.14 (2018-11-14)

特徴と改善
  • Improved exceptions and error handling on failures. #1977
  • Added persistent settings for all CLI flags via PIPENV_{FLAG_NAME} environment variables by enabling auto_envvar_prefix=PIPENV in click (implements PEEP-0002). #2200
  • Added improved messaging about available but skipped updates due to dependency conflicts when running pipenv update --outdated. #2411
  • Added environment variable PIPENV_PYUP_API_KEY to add ability to override the bundled pyup.io API key. #2825
  • Added additional output to pipenv update --outdated to indicate that the operation succeded and all packages were already up to date. #2828
  • Updated crayons patch to enable colors on native powershell but swap native blue for magenta. #3020
  • Added support for --bare to pipenv clean, and fixed pipenv sync --bare to actually reduce output. #3041
  • Added windows-compatible spinner via upgraded vistir dependency. #3089
    • Added support for python installations managed by asdf. #3096
  • Improved runtime performance of no-op commands such as pipenv --venv by around 2/3. #3158
  • Do not show error but success for running pipenv uninstall --all in a fresh virtual environment. #3170
  • Improved asynchronous installation and error handling via queued subprocess paralleization. #3217
バグ修正
  • Remote non-PyPI artifacts and local wheels and artifacts will now include their own hashes rather than including hashes from PyPI. #2394
  • Non-ascii characters will now be handled correctly when parsed by pipenv's ToML parsers. #2737
  • Updated pipenv uninstall to respect the --skip-lock argument. #2848
  • Fixed a bug which caused uninstallation to sometimes fail to successfullly remove packages from Pipfiles with comments on preceding or following lines. #2885, #3099
  • Pipenv will no longer fail when encountering python versions on Windows that have been uninstalled. #2983
  • Fixed unnecessary extras are added when translating markers #3026
  • Fixed a virtualenv creation issue which could cause new virtualenvs to inadvertently attempt to read and write to global site packages. #3047
  • Fixed an issue with virtualenv path derivation which could cause errors, particularly for users on WSL bash. #3055
  • Fixed a bug which caused Unexpected EOF errors to be thrown when pip was waiting for input from users who had put login credentials in environment variables. #3088
  • Fixed a bug in requirementslib which prevented successful installation from mercurial repositories. #3090
  • Fixed random resource warnings when using pyenv or any other subprocess calls. #3094
    • Fixed a bug which sometimes prevented cloning and parsing mercurial requirements. #3096
  • Fixed an issue in delegator.py related to subprocess calls when using PopenSpawn to stream output, which sometimes threw unexpected EOF errors. #3102, #3114, #3117
  • Fix the path casing issue that makes pipenv clean fail on Windows #3104
  • Pipenv will avoid leaving build artifacts in the current working directory. #3106
  • Fixed issues with broken subprocess calls leaking resource handles and causing random and sporadic failures. #3109
  • Fixed an issue which caused pipenv clean to sometimes clean packages from the base site-packages folder or fail entirely. #3113
  • Updated pythonfinder to correct an issue with unnesting of nested paths when searching for python versions. #3121
  • Added additional logic for ignoring and replacing non-ascii characters when formatting console output on non-UTF-8 systems. #3131
  • Fix virtual environment discovery when PIPENV_VENV_IN_PROJECT is set, but the in-project .venv is a file. #3134
  • Hashes for remote and local non-PyPI artifacts will now be included in Pipfile.lock during resolution. #3145
  • Fix project path hashing logic in purpose to prevent collisions of virtual environments. #3151
  • Fix package installation when the virtual environment path contains parentheses. #3158
  • Azure Pipelines YAML files are updated to use the latest syntax and product name. #3164
  • Fixed new spinner success message to write only one success message during resolution. #3183
  • Pipenv will now correctly respect the --pre option when used with pipenv install. #3185
  • Fix a bug where exception is raised when run pipenv graph in a project without created virtualenv #3201
  • When sources are missing names, names will now be derived from the supplied URL. #3216
Vendored Libraries
  • Updated pythonfinder to correct an issue with unnesting of nested paths when searching for python versions. #3061, #3121
  • Updated vendored dependencies:
    • certifi 2018.08.24 => 2018.10.15
    • urllib3 1.23 => 1.24
    • requests 2.19.1 => 2.20.0
    • shellingham ``1.2.6 => 1.2.7
    • tomlkit 0.4.4. => 0.4.6
    • vistir 0.1.6 => 0.1.8
    • pythonfinder 0.1.2 => 0.1.3
    • requirementslib 1.1.9 => 1.1.10
    • backports.functools_lru_cache 1.5.0 (new)
    • cursor 1.2.0 (new) #3089
  • Updated vendored dependencies:
    • requests 2.19.1 => 2.20.1
    • tomlkit 0.4.46 => 0.5.2
    • vistir 0.1.6 => 0.2.4
    • pythonfinder 1.1.2 => 1.1.8
    • requirementslib 1.1.10 => 1.3.0 #3096
  • Switch to tomlkit for parsing and writing. Drop prettytoml and contoml from vendors. #3191
  • Updated requirementslib to aid in resolution of local and remote archives. #3196
ドキュメントの改善
  • Expanded development and testing documentation for contributors to get started. #3074

2018.10.13 (2018-10-13)

バグ修正
  • Fixed a bug in pipenv clean which caused global packages to sometimes be inadvertently targeted for cleanup. #2849
  • Fix broken backport imports for vendored vistir. #2950, #2955, #2961
  • Fixed a bug with importing local vendored dependencies when running pipenv graph. #2952
  • Fixed a bug which caused executable discovery to fail when running inside a virtualenv. #2957
  • Fix parsing of outline tables. #2971
  • Fixed a bug which caused verify_ssl to fail to drop through to pip install correctly as trusted-host. #2979
  • Fixed a bug which caused canonicalized package names to fail to resolve against PyPI. #2989
  • Enhanced CI detection to detect Azure Devops builds. #2993
  • Fixed a bug which prevented installing pinned versions which used redirection symbols from the command line. #2998
  • Fixed a bug which prevented installing the local directory in non-editable mode. #3005
Vendored Libraries
  • Updated requirementslib to version 1.1.9. #2989
  • Upgraded pythonfinder => 1.1.1 and vistir => 0.1.7. #3007

2018.10.9 (2018-10-09)

特徴と改善
  • Added environment variables PIPENV_VERBOSE and PIPENV_QUIET to control output verbosity without needing to pass options. #2527
  • Updated test-pypi addon to better support json-api access (forward compatibility). Improved testing process for new contributors. #2568
  • Greatly enhanced python discovery functionality:
    • Added pep514 (windows launcher/finder) support for python discovery.
    • Introduced architecture discovery for python installations which support different architectures. #2582
  • Added support for pipenv shell on msys and cygwin/mingw/git bash for Windows. #2641
  • Enhanced resolution of editable and VCS dependencies. #2643
  • Deduplicate and refactor CLI to use stateful arguments and object passing. See this issue for reference. #2814
動作の変更
  • Virtual environment activation for run is revised to improve interpolation with other Python discovery tools. #2503
  • Improve terminal coloring to display better in Powershell. #2511
  • Invoke virtualenv directly for virtual environment creation, instead of depending on pew. #2518
  • pipenv --help will now include short help descriptions. #2542
  • Add COMSPEC to fallback option (along with SHELL and PYENV_SHELL) if shell detection fails, improving robustness on Windows. #2651
  • Fallback to shell mode if run fails with Windows error 193 to handle non-executable commands. This should improve usability on Windows, where some users run non-executable files without specifying a command, relying on Windows file association to choose the current command. #2718
バグ修正
  • Fixed a bug which prevented installation of editable requirements using ssh:// style urls #1393

  • VCS Refs for locked local editable dependencies will now update appropriately to the latest hash when running pipenv update. #1690

  • .tar.gz and .zip artifacts will now have dependencies installed even when they are missing from the lockfile. #2173

  • The command line parser will now handle multiple -e/--editable dependencies properly via click's option parser to help mitigate future parsing issues. #2279

  • Fixed the ability of pipenv to parse dependency_links from setup.py when PIP_PROCESS_DEPENDENCY_LINKS is enabled. #2434

  • Fixed a bug which could cause -i/--index arguments to sometimes be incorrectly picked up in packages. This is now handled in the command line parser. #2494

  • Fixed non-deterministic resolution issues related to changes to the internal package finder in pip 10. #2499, #2529, #2589, #2666, #2767, #2785, #2795, #2801, #2824, #2862, #2879, #2894, #2933

  • Fix subshell invocation on Windows for Python 2. #2515

  • Fixed a bug which sometimes caused pipenv to throw a TypeError or to run into encoding issues when writing lockfiles on python 2. #2561

  • Improve quoting logic for pipenv run so it works better with Windows built-in commands. #2563

  • Fixed a bug related to parsing vcs requirements with both extras and subdirectory fragments. Corrected an issue in the requirementslib parser which led to some markers being discarded rather than evaluated. #2564

  • Fixed multiple issues with finding the correct system python locations. #2582

  • Catch JSON decoding error to prevent exception when the lock file is of invalid format. #2607

  • Fixed a rare bug which could sometimes cause errors when installing packages with custom sources. #2610

  • Update requirementslib to fix a bug which could raise an UnboundLocalError when parsing malformed VCS URIs. #2617

  • Fixed an issue which prevented passing multiple --ignore parameters to pipenv check. #2632

  • Fixed a bug which caused attempted hashing of ssh:// style URIs which could cause failures during installation of private ssh repositories. - Corrected path conversion issues which caused certain editable VCS paths to be converted to ssh:// URIs improperly. #2639

  • Fixed a bug which caused paths to be formatted incorrectly when using pipenv shell in bash for windows. #2641

  • Dependency links to private repositories defined via ssh:// schemes will now install correctly and skip hashing as long as PIP_PROCESS_DEPENDENCY_LINKS=1. #2643

  • Fixed a bug which sometimes caused pipenv to parse the trusted_host argument to pip incorrectly when parsing source URLs which specify verify_ssl = false. #2656

  • Prevent crashing when a virtual environment in WORKON_HOME is faulty. #2676

  • Fixed virtualenv creation failure when a .venv file is present in the project root. #2680

  • Fixed a bug which could cause the -e/--editable argument on a dependency to be accidentally parsed as a dependency itself. #2714

  • Correctly pass verbose and debug flags to the resolver subprocess so it generates appropriate output. This also resolves a bug introduced by the fix to #2527. #2732

  • All markers are now included in pipenv lock --requirements output. #2748

  • Fixed a bug in marker resolution which could cause duplicate and non-deterministic markers. #2760

  • Fixed a bug in the dependency resolver which caused regular issues when handling setup.py based dependency resolution. #2766

  • Updated vendored dependencies:
    • pip-tools (updated and patched to latest w/ pip 18.0 compatibilty)
    • pip 10.0.1 => 18.0
    • click 6.7 => 7.0
    • toml 0.9.4 => 0.10.0
    • pyparsing 2.2.0 => 2.2.2
    • delegator 0.1.0 => 0.1.1
    • attrs 18.1.0 => 18.2.0
    • distlib 0.2.7 => 0.2.8
    • packaging 17.1.0 => 18.0
    • passa 0.2.0 => 0.3.1
    • pip_shims 0.1.2 => 0.3.1
    • plette 0.1.1 => 0.2.2
    • pythonfinder 1.0.2 => 1.1.0
    • pytoml 0.1.18 => 0.1.19
    • requirementslib 1.1.16 => 1.1.17
    • shellingham 1.2.4 => 1.2.6
    • tomlkit 0.4.2 => 0.4.4
    • vistir 0.1.4 => 0.1.6 #2802,

    #2867, #2880

  • Fixed a bug where pipenv crashes when the WORKON_HOME directory does not exist. #2877

  • Fixed pip is not loaded from pipenv's patched one but the system one #2912

  • Fixed various bugs related to pip 18.1 release which prevented locking, installation, and syncing, and dumping to a requirements.txt file. #2924

Vendored Libraries
  • Pew is no longer vendored. Entry point pewtwo, packages pipenv.pew and pipenv.patched.pew are removed. #2521

  • Update pythonfinder to major release 1.0.0 for integration. #2582

  • Update requirementslib to fix a bug which could raise an UnboundLocalError when parsing malformed VCS URIs. #2617

    • Vendored new libraries vistir and pip-shims, tomlkit, modutil, and plette.
    • Update vendored libraries: - scandir to 1.9.0 - click-completion to 0.4.1 - semver to 2.8.1 - shellingham to 1.2.4 - pytoml to 0.1.18 - certifi to 2018.8.24 - ptyprocess to 0.6.0 - requirementslib to 1.1.5 - pythonfinder to 1.0.2 - pipdeptree to 0.13.0 - python-dotenv to 0.9.1 #2639
  • Updated vendored dependencies:
    • pip-tools (updated and patched to latest w/ pip 18.0 compatibilty)
    • pip 10.0.1 => 18.0
    • click 6.7 => 7.0
    • toml 0.9.4 => 0.10.0
    • pyparsing 2.2.0 => 2.2.2
    • delegator 0.1.0 => 0.1.1
    • attrs 18.1.0 => 18.2.0
    • distlib 0.2.7 => 0.2.8
    • packaging 17.1.0 => 18.0
    • passa 0.2.0 => 0.3.1
    • pip_shims 0.1.2 => 0.3.1
    • plette 0.1.1 => 0.2.2
    • pythonfinder 1.0.2 => 1.1.0
    • pytoml 0.1.18 => 0.1.19
    • requirementslib 1.1.16 => 1.1.17
    • shellingham 1.2.4 => 1.2.6
    • tomlkit 0.4.2 => 0.4.4
    • vistir 0.1.4 => 0.1.6 #2902,

    #2935

ドキュメントの改善
  • Simplified the test configuration process. #2568
  • Updated documentation to use working fortune cookie addon. #2644
  • Added additional information about troubleshooting pipenv shell by using the the $PIPENV_SHELL environment variable. #2671
  • Added a link to PEP-440 version specifiers in the documentation for additional detail. #2674
  • Added simple example to README.md for installing from git. #2685
  • Stopped recommending --system for Docker contexts. #2762
  • Fixed the example url for doing "pipenv install -e some-repo-url#egg=something", it was missing the "egg=" in the fragment identifier. #2792
  • Fixed link to the "be cordial" essay in the contribution documentation. #2793
  • Clarify pipenv install documentation #2844
  • Replace reference to uservoice with PEEP-000 #2909

2018.7.1 (2018-07-01)

特徴と改善
  • All calls to pipenv shell are now implemented from the ground up using shellingham, a custom library which was purpose built to handle edge cases and shell detection. #2371
  • Added support for python 3.7 via a few small compatibility / bugfixes. #2427, #2434, #2436
  • Added new flag pipenv --support to replace the diagnostic command python -m pipenv.help. #2477, #2478
  • Improved import times and CLI runtimes with minor tweaks. #2485
バグ修正
  • Fixed an ongoing bug which sometimes resolved incompatible versions into lockfiles. #1901
  • Fixed a bug which caused errors when creating virtualenvs which contained leading dash characters. #2415
  • Fixed a logic error which caused --deploy --system to overwrite editable vcs packages in the pipfile before installing, which caused any installation to fail by default. #2417
  • Updated requirementslib to fix an issue with properly quoting markers in VCS requirements. #2419
  • Installed new vendored jinja2 templates for click-completion which were causing template errors for users with completion enabled. #2422
  • Added support for python 3.7 via a few small compatibility / bugfixes. #2427
  • Fixed an issue reading package names from setup.py files in projects which imported utilities such as versioneer. #2433
  • Pipenv will now ensure that its internal package names registry files are written with unicode strings. #2450
  • Fixed a bug causing requirements input as relative paths to be output as absolute paths or URIs. Fixed a bug affecting normalization of git+git@host uris. #2453
  • Pipenv will now always use pathlib2 for Path based filesystem interactions by default on python<3.5. #2454
  • Fixed a bug which prevented passing proxy PyPI indexes set with --pypi-mirror from being passed to pip during virtualenv creation, which could cause the creation to freeze in some cases. #2462
  • Using the python -m pipenv.help command will now use proper encoding for the host filesystem to avoid encoding issues. #2466
  • The new jinja2 templates for click_completion will now be included in pipenv source distributions. #2479
  • Resolved a long-standing issue with re-using previously generated InstallRequirement objects for resolution which could cause PKG-INFO file information to be deleted, raising a TypeError. #2480
  • Resolved an issue parsing usernames from private PyPI URIs in Pipfiles by updating requirementslib. #2484
Vendored Libraries
  • All calls to pipenv shell are now implemented from the ground up using shellingham, a custom library which was purpose built to handle edge cases and shell detection. #2371
  • Updated requirementslib to fix an issue with properly quoting markers in VCS requirements. #2419
  • Installed new vendored jinja2 templates for click-completion which were causing template errors for users with completion enabled. #2422
  • Add patch to prettytoml to support Python 3.7. #2426
  • Patched prettytoml.AbstractTable._enumerate_items to handle StopIteration errors in preparation of release of python 3.7. #2427
  • Fixed an issue reading package names from setup.py files in projects which imported utilities such as versioneer. #2433
  • Updated requirementslib to version 1.0.9 #2453
  • Unraveled a lot of old, unnecessary patches to pip-tools which were causing non-deterministic resolution errors. #2480
  • Resolved an issue parsing usernames from private PyPI URIs in Pipfiles by updating requirementslib. #2484
ドキュメントの改善
  • Added instructions for installing using Fedora's official repositories. #2404

2018.6.25 (2018-06-25)

特徴と改善
  • Pipenv-created virtualenvs will now be associated with a .project folder (features can be implemented on top of this later or users may choose to use pipenv-pipes to take full advantage of this.) #1861
  • Virtualenv names will now appear in prompts for most Windows users. #2167
  • Added support for cmder shell paths with spaces. #2168
  • Added nested JSON output to the pipenv graph command. #2199
  • Dropped vendored pip 9 and vendored, patched, and migrated to pip 10. Updated patched piptools version. #2255
  • PyPI mirror URLs can now be set to override instances of PyPI urls by passing the --pypi-mirror argument from the command line or setting the PIPENV_PYPI_MIRROR environment variable. #2281
  • Virtualenv activation lines will now avoid being written to some shell history files. #2287
  • Pipenv will now only search for requirements.txt files when creating new projects, and during that time only if the user doesn't specify packages to pass in. #2309
  • Added support for mounted drives via UNC paths. #2331
  • Added support for Windows Subsystem for Linux bash shell detection. #2363
  • Pipenv will now generate hashes much more quickly by resolving them in a single pass during locking. #2384
  • pipenv run will now avoid spawning additional COMSPEC instances to run commands in when possible. #2385
  • Massive internal improvements to requirements parsing codebase, resolver, and error messaging. #2388
  • pipenv check now may take multiple of the additional argument --ignore which takes a parameter cve_id for the purpose of ignoring specific CVEs. #2408
動作の変更
  • Pipenv will now parse & capitalize platform_python_implementation markers .. warning:: This could cause an issue if you have an out of date Pipfile which lowercases the comparison value (e.g. cpython instead of CPython). #2123
  • Pipenv will now only search for requirements.txt files when creating new projects, and during that time only if the user doesn't specify packages to pass in. #2309
バグ修正
  • Massive internal improvements to requirements parsing codebase, resolver, and error messaging. #1962, #2186, #2263, #2312
  • Pipenv will now parse & capitalize platform_python_implementation markers. #2123
  • Fixed a bug with parsing and grouping old-style setup.py extras during resolution #2142
  • Fixed a bug causing pipenv graph to throw unhelpful exceptions when running against empty or non-existent environments. #2161
  • Fixed a bug which caused --system to incorrectly abort when users were in a virtualenv. #2181
  • Removed vendored cacert.pem which could cause issues for some users with custom certificate settings. #2193
  • Fixed a regression which led to direct invocations of virtualenv, rather than calling it by module. #2198
  • Locking will now pin the correct VCS ref during pipenv update runs. Running pipenv update with a new vcs ref specified in the Pipfile will now properly obtain, resolve, and install the specified dependency at the specified ref. #2209
  • pipenv clean will now correctly ignore comments from pip freeze when cleaning the environment. #2262
  • Resolution bugs causing packages for incompatible python versions to be locked have been fixed. #2267
  • Fixed a bug causing pipenv graph to fail to display sometimes. #2268
  • Updated requirementslib to fix a bug in pipfile parsing affecting relative path conversions. #2269
  • Windows executable discovery now leverages os.pathext. #2298
  • Fixed a bug which caused --deploy --system to inadvertently create a virtualenv before failing. #2301
  • Fixed an issue which led to a failure to unquote special characters in file and wheel paths. #2302
  • VCS dependencies are now manually obtained only if they do not match the requested ref. #2304
  • Added error handling functionality to properly cope with single-digit Requires-Python metatdata with no specifiers. #2377
  • pipenv update will now always run the resolver and lock before ensuring your dependencies are in sync with your lockfile. #2379
  • Resolved a bug in our patched resolvers which could cause nondeterministic resolution failures in certain conditions. Running pipenv install with no arguments in a project with only a Pipfile will now correctly lock first for dependency resolution before installing. #2384
  • Patched python-dotenv to ensure that environment variables always get encoded to the filesystem encoding. #2386
ドキュメントの改善
  • Update documentation wording to clarify Pipenv's overall role in the packaging ecosystem. #2194
  • Added contribution documentation and guidelines. #2205
  • Added instructions for supervisord compatibility. #2215
  • Fixed broken links to development philosophy and contribution documentation. #2248
Vendored Libraries
  • Removed vendored cacert.pem which could cause issues for some users with custom certificate settings. #2193

  • Dropped vendored pip 9 and vendored, patched, and migrated to pip 10. Updated patched piptools version. #2255

  • Updated requirementslib to fix a bug in pipfile parsing affecting relative path conversions. #2269

  • Added custom shell detection library shellingham, a port of our changes to pew. #2363

  • Patched python-dotenv to ensure that environment variables always get encoded to the filesystem encoding. #2386

  • Updated vendored libraries. The following vendored libraries were updated:

    • distlib from version 0.2.6 to 0.2.7.
    • jinja2 from version 2.9.5 to 2.10.
    • pathlib2 from version 2.1.0 to 2.3.2.
    • parse from version 2.8.0 to 2.8.4.
    • pexpect from version 2.5.2 to 2.6.0.
    • requests from version 2.18.4 to 2.19.1.
    • idna from version 2.6 to 2.7.
    • certifi from version 2018.1.16 to 2018.4.16.
    • packaging from version 16.8 to 17.1.
    • six from version 1.10.0 to 1.11.0.
    • requirementslib from version 0.2.0 to 1.0.1.

    In addition, scandir was vendored and patched to avoid importing host system binaries when falling back to pathlib2. #2368

ユーザーによる推薦文

David Gang
このパッケージマネージャーは本当に素晴しい。 どんな依存関係があり、そのうちのどれが私がインストールしたもので、どれが推移的依存関係なのかを初めて認識できた。 インストールが決定論的であることも相俟って、cargoのような一級品のパッケージマネージャーとなっている
Justin Myles Holmes
Pipenvは遂に、単なるファイルシステムとではなく思考と結び付くための抽象化を果たした。

☤ Pipenvの特徴

  • 何をしたいか を簡単に指定するだけで、真の 決定論的ビルド が可能です。
  • 固定された依存関係のファイルハッシュを生成しチェックします。
  • pyenv が使える場合は、要求されているPythonを自動でインストールします。
  • Pipfile を探して、再帰的に、プロジェクトホームを自動で見付けに行きます。
  • Pipfile が存在していない場合、自動で生成します。
  • 標準的な場所に仮想環境を自動で作成します。
  • パッケージがインストールもしくはアンインストールされたときに、自動で Pipfile に追加および削除します。
  • .env ファイルが存在する場合、自動で読み込みます。

主なコマンドは installuninstalllock で、lock コマンドは Pipfile.lock を生成します。 これらは、手動での仮想環境の管理 (仮想環境を有効にするための $ pipenv shell の実行) だけでなく、 $ pip install の使用も置き換えるために作られています。

基本コンセプト

  • 既存の仮想環境が存在しないときは、自動で作成されます。
  • install にパラメータが何も渡されないときは、 [packages] に指定された全てのパッケージがインストールされます。
  • Python 3の仮想環境を初期化するには、 $ pipenv --three を実行します。
  • Python 2の仮想環境を初期化するには、 $ pipenv --two を実行します。
  • それ以外は、virtualenvがデフォルトとしているものをPipenvのデフォルトとします。

他のコマンド

  • graph はインストールされた依存パッケージの依存関係グラフを表示します。
  • shell will spawn a shell with the virtualenv activated. This shell can be deactivated by using exit.
  • run は、与えられたコマンドに任意の引数を付けて仮想環境で実行します(例えば $ pipenv run python$ pipenv run pip freeze)。
  • check はセキュリティの脆弱性をチェックし、現在の環境がPEP 508の要求仕様を満たしていることを表明します。

より進んだ内容のドキュメントガイド

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.

Pipenvの進んだ使い方

https://farm4.staticflickr.com/3672/33231486560_bff4124c9a_k_d.jpg

このドキュメントではPipenvのより輝かしい進んだ機能を対象としています。

☤ 注意書き

  • Pipfile にある依存パッケージのwheelは $ pipenv lock では捕捉されません。
  • There are some known issues with using private indexes, related to hashing. We're actively working to solve this problem. You may have great luck with this, however.
  • インストールはできる限り決定論的になるようになっています — 問題が出た場合には --sequential フラグを使ってより決定論的に振る舞うようにしてください。

☤ パッケージの一覧を指定する

特定のパッケージ一覧で特定のパッケージをインストールしたい場合は、次のように指定できます:

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

[[source]]
url = "http://pypi.home.kennethreitz.org/simple"
verify_ssl = false
name = "home"

[dev-packages]

[packages]
requests = {version="*", index="home"}
maya = {version="*", index="pypi"}
records = "*"

めっちゃ高機能。

☤ PyPIミラーを使う

デフォルトのPyPIインデックスのURLをPyPIミラーのURLで上書きしたい場合は、次のオプションが使えます:

$ pipenv install --pypi-mirror <mirror_url>

$ pipenv update --pypi-mirror <mirror_url>

$ pipenv sync --pypi-mirror <mirror_url>

$ pipenv lock --pypi-mirror <mirror_url>

$ pipenv uninstall --pypi-mirror <mirror_url>

その他にも、PIPENV_PYPI_MIRROR 環境変数を設定することもできます。

☤ 環境変数でPipfileにクレデンシャルを差し込む

Pipenvは (定義されていれば) Pipfileにある環境変数を展開します。 この機能はプライベートのPyPIで認証する必要がある場合に非常に便利です:

[[source]]
url = "https://$USERNAME:${PASSWORD}@mypypi.example.com/simple"
verify_ssl = true
name = "pypi"

幸運なことに、Pipenvは環境変数を展開する 前に Pipfileのハッシュを取ります (そしてありがたいことに、ロックファイルからインストールするときは、再び環境変数が置き換えられます。そのため秘匿情報をコミットする必要は無いのです! やったー!)

If your credentials contain a special character, surround the references to the environment variables with quotation marks. For example, if your password contain a double quotation mark, surround the password variable with single quotation marks. Otherwise, you may get a ValueError, "No closing quotation" error while installing dependencies.

[[source]]
url = "https://$USERNAME:'${PASSWORD}'@mypypi.example.com/simple"

☤ 基本的な事項の指定

ある特定のパッケージをあるシステムだけにインストールしたい場合は、 PEP 508 指示子 を使って実現できます。

これが、 Windowsシステムだけに pywinusb をインストールする Pipfile の例です:

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

[packages]
requests = "*"
pywinusb = {version = "*", sys_platform = "== 'win32'"}

ほら、見て!

これがもっと複雑な例です:

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

[packages]
unittest2 = {version = ">=1.0,<3.0", markers="python_version < '2.7.9' or (python_version >= '3.0' and python_version < '3.4')"}

魔法です。純粋な、混じり気の無い魔法です。

☤ pipenvをデプロイで使う

デプロイ手順の一部として pipenv を使いたい場合もあるでしょう。

--deploy フラグを使うと強制的に Pipfile.lock を最新にできます:

$ pipenv install --deploy

このフラグを立てると、 Pipfile.lock が古くなっている場合に、Pipfile.lock を新しく生成するのではなく、ビルドが失敗します。

そうでない場合は、sync コマンドを使って Pipfile.lock の指定どおりにパッケージがインストールされます:

$ pipenv sync

注釈

pipenv install --ignore-pipfile is nearly equivalent to pipenv sync, but pipenv sync will never attempt to re-lock your dependencies as it is considered an atomic operation. pipenv install by default does attempt to re-lock unless using the --deploy flag.

システム環境への依存関係のデプロイ

--system フラグを使って、Pipfileの内容にあるものを親システムにインストールするようPipenvに指示できます:

$ pipenv install --system

これはシステム環境のPythonの管理やデプロイのためのインフラで役に立ちます (例えば、Herokuで使われています)。

☤ PipenvとCPython以外のPythonディストリビューション

サードパーティーのPythonディストリビューション (例えば、Anaconda) でPipenvを使うには、Pythonバイナリへのパスを与えるだけでよいです:

$ pipenv install --python=/path/to/python

AnacondaはCondaでパッケージを管理しています。 CondaでインストールしたPythonのパッケージを再利用するには、 --site-packages フラグを使ってください:

$ pipenv --python=/path/to/python --site-packages

requirements.txt の生成

PipfilePipfile.lockrequirements.txt に非常に簡単に変換でき、追加機能や素敵な機能など既に実装された機能全ての恩恵を受けられます。

この Pipfile から:

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

[packages]
requests = {version="*"}

requirements.txt を生成しましょう:

$ pipenv lock -r
chardet==3.0.4
requests==2.18.4
certifi==2017.7.27.1
idna==2.6
urllib3==1.22

開発用の依存関係だけの requirements.txt を生成したいと思った場合は、それも可能です! 次の Pipfile を用意しましょう:

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

[dev-packages]
pytest = {version="*"}

requirements.txt を生成しましょう:

$ pipenv lock -r --dev
py==1.4.34
pytest==3.2.3

めっちゃ高機能。

☤ セキュリティの脆弱性の検知

Pipenv は safety パッケージを含んでいて、既知のセキュリティの脆弱性が無いか依存関係グラフを走査するのに使われます。

例:

$ cat Pipfile
[packages]
django = "==1.10.1"

$ pipenv check
Checking PEP 508 requirements…
Passed!
Checking installed package safety…

33075: django >=1.10,<1.10.3 resolved (1.10.1 installed)!
Django before 1.8.x before 1.8.16, 1.9.x before 1.9.11, and 1.10.x before 1.10.3, when settings.DEBUG is True, allow remote attackers to conduct DNS rebinding attacks by leveraging failure to validate the HTTP Host header against settings.ALLOWED_HOSTS.

33076: django >=1.10,<1.10.3 resolved (1.10.1 installed)!
Django 1.8.x before 1.8.16, 1.9.x before 1.9.11, and 1.10.x before 1.10.3 use a hardcoded password for a temporary database user created when running tests with an Oracle database, which makes it easier for remote attackers to obtain access to the database server by leveraging failure to manually specify a password in the database settings TEST dictionary.

33300: django >=1.10,<1.10.7 resolved (1.10.1 installed)!
CVE-2017-7233: Open redirect and possible XSS attack via user-supplied numeric redirect URLs
============================================================================================

Django relies on user input in some cases  (e.g.
:func:`django.contrib.auth.views.login` and :doc:`i18n </topics/i18n/index>`)
to redirect the user to an "on success" URL. The security check for these
redirects (namely ``django.utils.http.is_safe_url()``) considered some numeric
URLs (e.g. ``http:999999999``) "safe" when they shouldn't be.

Also, if a developer relies on ``is_safe_url()`` to provide safe redirect
targets and puts such a URL into a link, they could suffer from an XSS attack.

CVE-2017-7234: Open redirect vulnerability in ``django.views.static.serve()``
=============================================================================

A maliciously crafted URL to a Django site using the
:func:`~django.views.static.serve` view could redirect to any other domain. The
view no longer does any redirects as they don't provide any known, useful
functionality.

Note, however, that this view has always carried a warning that it is not
hardened for production use and should be used only as a development aid.

✨🍰✨

注釈

In order to enable this functionality while maintaining its permissive copyright license, pipenv embeds an API client key for the backend Safety API operated by pyup.io rather than including a full copy of the CC-BY-NC-SA licensed Safety-DB database. This embedded client key is shared across all pipenv check users, and hence will be subject to API access throttling based on overall usage rather than individual client usage.

You can also use your own safety API key by setting the environment variable PIPENV_PYUP_API_KEY.

☤ コミュニティとの連係

Pipenvと連係する様々なプロダクトに加え、コミュニティがメンテナンスしている多種多様のプラグインや拡張があり、様々なエディタやIDEで使えます:

対応中:

  • Sublime Text (エディタ連係)
  • 未だその姿を見せていない来たるべきGoogle Cloudプロダクト (クラウドホスティング)

☤ エディタでモジュールを開く

Pipenvを使うと $ pipenv open コマンドで、(自分で書いたコードベースを含め) インストールされているどんなPythonモジュールも開けます:

$ pipenv install -e git+https://github.com/kennethreitz/background.git#egg=background
Installing -e git+https://github.com/kennethreitz/background.git#egg=background…
...
Updated Pipfile.lock!

$ pipenv open background
Opening '/Users/kennethreitz/.local/share/virtualenvs/hmm-mGOawwm_/src/background/background.py' in your EDITOR.

この機能のおかげで、GitHubまで見に行かなくても、今使っているコードを手軽に読めるようになります。

注釈

この機能では標準の EDITOR 環境変数が使われます。 例えばVS Codeを使っている場合は、 export EDITOR=code とします (macOSの場合は、最初に PATH に上 コマンドをインストール します)。

☤ Pythonの自動インストール

pyenv のインストールと設定が済んでいて、必要とするバージョンのPythonがまだ利用できる状態になっていない場合、Pipenvは自動でそのバージョンのPythonをインストールしたいかどうかを尋ねます。

これは非常に高度な機能で、自慢の機能です:

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

[dev-packages]

[packages]
requests = "*"

[requires]
python_version = "3.6"

$ pipenv install
Warning: Python 3.6 was not found on your system…
Would you like us to install latest CPython 3.6 with pyenv? [Y/n]: y
Installing CPython 3.6.2 with pyenv (this may take a few minutes)…
...
Making Python installation global…
Creating a virtualenv for this project…
Using /Users/kennethreitz/.pyenv/shims/python3 to create virtualenv…
...
No package provided, installing all dependencies.
...
Installing dependencies from Pipfile.lock…
🐍   ❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒❒ 5/5 — 00:00:03
To activate this project's virtualenv, run the following:
 $ pipenv shell

Pipenv は PEP 508 が規定する python_full_versionpython_version の両方に従います。

💫✨🍰✨💫

.env の自動読み込み

プロジェクトに .env ファイルが存在する場合は、 $ pipenv shell および $ pipenv run は自動で読み込みます:

$ cat .env
HELLO=WORLD⏎

$ pipenv run python
Loading .env environment variables…
Python 2.7.13 (default, Jul 18 2017, 09:17:00)
[GCC 4.2.1 Compatible Apple LLVM 8.1.0 (clang-802.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['HELLO']
'WORLD'

Shell like variable expansion is available in .env files using ${VARNAME} syntax.:

$ cat .env
CONFIG_PATH=${HOME}/.config/foo

$ pipenv run python
Loading .env environment variables…
Python 3.7.6 (default, Dec 19 2019, 22:52:49)
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['CONFIG_PATH']
'/home/kennethreitz/.config/foo'

この機能は、本番環境の証明書をコードベースから避けておくのに非常に便利です。 .env ファイルをソースコード管理にコミットするのはお薦めしません!

.env が別のパスに置いてあったり、別のファイル名の場合は、 PIPENV_DOTENV_LOCATION 環境変数を設定します:

$ PIPENV_DOTENV_LOCATION=/path/to/.env pipenv shell

Pipenvが .env ファイルを読み込まないようにするには、 PIPENV_DONT_LOAD_ENV 環境変数を設定します:

$ PIPENV_DONT_LOAD_ENV=1 pipenv shell

See theskumar/python-dotenv for more information on .env files.

☤ 独自のスクリプトショートカット

Pipenvは、Pipfileのオプションの [scripts] 節で独自のショートカットの作成をサポートしています。

そのショートカットは、ターミナルで pipenv run <shortcut name> と実行でき、Pipenvシェルを事前に有効化してなかったとしてもPipenvの仮想環境のコンテキストでコマンドが実行されます。

For example, in your Pipfile:

[scripts]
printspam = "python -c \"print('I am a silly example, no one would need to do this')\""

そして、ターミナルで次のように打ち込みます:

$ pipenv run printspam
I am a silly example, no one would need to do this

Commands that expect arguments will also work. For example:

[scripts]
echospam = "echo I am really a very silly example"
$ pipenv run echospam "indeed"
I am really a very silly example indeed

☤ 環境変数のサポート

Pipenv supports the usage of environment variables in place of authentication fragments in your Pipfile. These will only be parsed if they are present in the [[source]] section. For example:

[[source]]
url = "https://${PYPI_USERNAME}:${PYPI_PASSWORD}@my_private_repo.example.com/simple"
verify_ssl = true
name = "pypi"

[dev-packages]

[packages]
requests = {version="*", index="home"}
maya = {version="*", index="pypi"}
records = "*"

Environment variables may be specified as ${MY_ENVAR} or $MY_ENVAR.

On Windows, %MY_ENVAR% is supported in addition to ${MY_ENVAR} or $MY_ENVAR.

☤ 環境変数による設定

Pipenvには、シェル環境変数で有効にできるオプションが少しだけあります。 オプションを有効にするには、シェルでその変数を作成すればpipevnが見付けてくれます。

pipenv.environments.PIPENV_CACHE_DIR = '/home/docs/.cache/pipenv'

Pipenvがパッケージキャッシュを保存する場所です。

Default is to use appdir's user cache directory.

pipenv.environments.PIPENV_COLORBLIND = False

設定された場合、ターミナル出力に色が付きません。

なんらか理由で、ターミナル出力に色が付いて欲しくない人もいます。 デフォルトでは色が付きます。

pipenv.environments.PIPENV_DEFAULT_PYTHON_VERSION = None

新しい仮想環境を作るときに、デフォルトでこのバージョンのPythonが使われます。

This can be set to a version string, e.g. 3.6, or a path. Default is to use whatever Python Pipenv is installed under (i.e. sys.executable). Command line flags (e.g. --python, --three, and --two) are prioritized over this configuration.

pipenv.environments.PIPENV_DONT_LOAD_ENV = False

設定された場合、Pipenvは .env ファイルを読み込みません。

デフォルトでは、 run コマンドと shell コマンドで .env が読み込まれます。

pipenv.environments.PIPENV_DONT_USE_ASDF = False

If set, Pipenv does not attempt to install Python with asdf.

Default is to install Python automatically via asdf when needed, if possible.

pipenv.environments.PIPENV_DONT_USE_PYENV = False

設定された場合、PipenvはpyenvでPythonをインストールしようとはしなくなります。

デフォルトでは、可能なら必要なときにpyenvで自動的にPythonをインストールします。

pipenv.environments.PIPENV_DOTENV_LOCATION = None

設定された場合、Pipenvは指定された場所の .env を読み込みます。

デフォルトでは、もしあればプロジェクトルートから .env を読み込みます。

pipenv.environments.PIPENV_EMULATOR = ''

設定された場合、ターミナルエミュレーターの名前に pipenv shell が使われます。

デフォルトでは、エミュレーターを自動的に検出します。 例えばCmderなどの正しく検出されないエミュレーターの場合は、この環境変数を設定すべきです。

pipenv.environments.PIPENV_HIDE_EMOJIS = False

出力に絵文字を使いません。

デフォルトでは、絵文字を使います。 Windowsでは自動的に設定されます。

pipenv.environments.PIPENV_IGNORE_VIRTUALENVS = False

If set, Pipenv will always assign a virtual environment for this project.

デフォルトでは、Pipenvは仮想環境内で実行されているかどうかを検出し、できる限り再利用します。 通常、これが望ましい振る舞いで、ユーザーが好きに構築した仮想環境をPipenvで使えるようにします。

pipenv.environments.PIPENV_INSTALL_TIMEOUT = 900

パッケージのインストールが完了するのを待つ最大秒数です。

Defaults to 900 (15 minutes), a very long arbitrary time.

pipenv.environments.PIPENV_MAX_DEPTH = 4

Pipfileを再帰的に探しに行くディレクトリ数の最大値です。

デフォルトでは、3です。 PIPENV_NO_INHERIT も参照してください。

pipenv.environments.PIPENV_MAX_RETRIES = 0

Specify how many retries Pipenv should attempt for network requests.

Default is 0. Automatically set to 1 on CI environments for robust testing.

pipenv.environments.PIPENV_MAX_ROUNDS = 16

Tells Pipenv how many rounds of resolving to do for Pip-Tools.

Default is 16, an arbitrary number that works most of the time.

pipenv.environments.PIPENV_MAX_SUBPROCESS = 8

How many subprocesses should Pipenv use when installing.

Default is 16, an arbitrary number that seems to work.

pipenv.environments.PIPENV_NOSPIN = False

If set, disable terminal spinner.

This can make the logs cleaner. Automatically set on Windows, and in CI environments.

pipenv.environments.PIPENV_NO_INHERIT = False

Tell Pipenv not to inherit parent directories.

This is useful for deployment to avoid using the wrong current directory. Overwrites PIPENV_MAX_DEPTH.

pipenv.environments.PIPENV_PIPFILE = None

If set, this specifies a custom Pipfile location.

When running pipenv from a location other than the same directory where the Pipfile is located, instruct pipenv to find the Pipfile in the location specified by this environment variable.

Default is to find Pipfile automatically in the current and parent directories. See also PIPENV_MAX_DEPTH.

pipenv.environments.PIPENV_PYPI_MIRROR = None

If set, tells pipenv to override PyPI index urls with a mirror.

Default is to not mirror PyPI, i.e. use the real one, pypi.org. The --pypi-mirror command line flag overwrites this.

pipenv.environments.PIPENV_RESOLVE_VCS = False

Tells Pipenv whether to resolve all VCS dependencies in full.

As of Pipenv 2018.11.26, only editable VCS dependencies were resolved in full. To retain this behavior and avoid handling any conflicts that arise from the new approach, you may set this to '0', 'off', or 'false'.

pipenv.environments.PIPENV_SHELL = None

An absolute path to the preferred shell for pipenv shell.

Default is to detect automatically what shell is currently in use.

pipenv.environments.PIPENV_SHELL_FANCY = False

If set, always use fancy mode when invoking pipenv shell.

Default is to use the compatibility shell if possible.

pipenv.environments.PIPENV_SKIP_LOCK = False

If set, Pipenv won't lock dependencies automatically.

This might be desirable if a project has large number of dependencies, because locking is an inherently slow operation.

Default is to lock dependencies and update Pipfile.lock on each run.

NOTE: This only affects the install and uninstall commands.

pipenv.environments.PIPENV_SPINNER = 'dots'

Sets the default spinner type.

Spinners are identitcal to the node.js spinners and can be found at https://github.com/sindresorhus/cli-spinners

pipenv.environments.PIPENV_TIMEOUT = 120

Max number of seconds Pipenv will wait for virtualenv creation to complete.

Default is 120 seconds, an arbitrary number that seems to work.

pipenv.environments.PIPENV_VENV_IN_PROJECT = False

If set, creates .venv in your project directory.

Default is to create new virtual environments in a global location.

pipenv.environments.PIPENV_YES = False

If set, Pipenv automatically assumes "yes" at all prompts.

Default is to prompt the user for an answer if the current command line session if interactive.

pipenv.environments.PIP_EXISTS_ACTION = 'w'

Specifies the value for pip's --exists-action option

Defaullts to (w)ipe

pipenv.environments.is_in_virtualenv()[ソース]

Check virtualenv membership dynamically

戻り値:True or false depending on whether we are in a regular virtualenv or not
戻り値の型:bool

これらの環境変数をプロジェクトごとの設定にしたい場合は、それを実現するために素敵な direnv を利用するのをお薦めします。

さらにカスタマイズする必要がある場合は、 pip自身も環境変数をサポートしている ことに着目してください。

例えば、次のようにできます:

$ PIP_INSTALL_OPTION="-- -DCMAKE_BUILD_TYPE=Release" pipenv install -e .

☤ 仮想環境の独自の配置場所

Pipenv automatically honors the WORKON_HOME environment variable, if you have it set — so you can tell pipenv to store your virtual environments wherever you want, e.g.:

export WORKON_HOME=~/.venvs

さらに、 PIPENV_VENV_IN_PROJECT 環境変数を設定することで、 project/.venv にある仮想環境をPipenvに使わせることができます。

☤ プロジェクトのテスト

Pipenvは Requests のようなプロジェクトで開発用の依存関係の宣言とテストスイートの実行に使われています。

現時点では Travis-CItox の両方で上手くデプロイのテストを行えています。

Travis CI

Travis CIの設定例は Requests にあります。 このプロジェクトではMakefileによく使う関数を init コマンドや tests コマンドとして定義してあります。 以下が .travis.yml の本質的なところを抜き出したものです:

language: python
python:
    - "2.6"
    - "2.7"
    - "3.3"
    - "3.4"
    - "3.5"
    - "3.6"
    - "3.7-dev"

# command to install dependencies
install: "make"

# command to run tests
script:
    - make test

そして対応するMakefileは以下の通りです:

init:
    pip install pipenv
    pipenv install --dev

test:
    pipenv run pytest tests
ToX自動化プロジェクト

または、 tox.ini を次のようにローカル環境でのテストと外部環境でのテストの両方に対して設定できます:

[tox]
envlist = flake8-py3, py26, py27, py33, py34, py35, py36, pypy

[testenv]
deps = pipenv
commands=
    pipenv install --dev
    pipenv run pytest tests

[testenv:flake8-py3]
basepython = python3.4
commands=
    pipenv install --dev
    pipenv run flake8 --version
    pipenv run flake8 setup.py docs project test

Pipenv will automatically use the virtualenv provided by tox. If pipenv install --dev installs e.g. pytest, then installed command pytest will be present in given virtualenv and can be called directly by pytest tests instead of pipenv run pytest tests.

テストを実行するたびにうっかりlockファイルを編集してしまわないように、 pipenv install--ignore-pipfile を付けたいと思うかもしれません。 これをするとPipenvが Pipfile への変更を無視してしまうのと、(もっと重要なこととして) 現在の環境を Pipfile.lock に追加するのを防ぎます。 これが重要な点なのは、今いる環境 (すなわちtoxが用意した仮想環境) は通常は (望ましいもしくは望しくないことに) 現時点のプロジェクトと、 toxdeps に設定されている追加の依存関係を含んでいるためです。 最初に用意される環境に対しては、この方法ではなく skip_install = True をtox.iniに追加することで無効化できます。

この方法はlockファイルの更新に関しての明示的な指定が必要であり、おそらくこれがどのケースにおいても良い案です。

サードパーティのプラグイン tox-pipenv も、toxにPipenvを連係させるのに使えます。

☤ シェルの補完

fishで補完を有効にするには、次のコマンドを設定ファイルに追加してください:

eval (pipenv --completion)

また、bashやzshでは次のコマンドを設定ファイルに追加してください:

eval "$(pipenv --completion)"

魔法のシェル補完が使えるようになりました!

✨🍰✨

☤ プラットフォームが提供するPythonコンポーネントを使っての作業

オペレーティングシステムのインターフェースに使われているプラットフォーム固有のPythonは、システムのパッケージマネージャからしか利用できず、従って pip を使った仮想環境へのインストールには使えないのが合理的に考えて普通です。 このようなケースでは、システムの site-packages ディレクトリにアクセスできる仮想環境を作ります:

$ pipenv --three --site-packages

pip でインストールできるコンポーネントが本当に仮想環境にインストールされ、システムのパッケージはPythonレベルでの依存関係解決に一切現れないインターフェースのために使われることを保証するために、 PIP_IGNORE_INSTALLED 設定を使いましょう:

$ PIP_IGNORE_INSTALLED=1 pipenv install --dev

☤ Pipfile vs setup.py

アプリケーションライブラリ の間には、微妙だが非常に重要な違いがあります。 これはPythonコミュニティでよく起こる混乱の元になっています。

ライブラリは、再利用可能な機能を他のライブラリやアプリケーション (ここでは両方を包括する用語として プロジェクト を使います) に提供します。 ライブラリは、自身を起点とする依存関係である他のライブラリと共に協調して動作する必要があります。 ライブラリは 抽象的な依存関係 を定義します。 プロジェクトに含まれる別々のライブラリのそれぞれを起点とする依存関係どうしで、バージョンの衝突が起きないようにライブラリは絶対に依存パッケージのバージョンを固定するべきではありません。 ある特定の機能や修正やバグに依存している場合には、バージョンの下限や (滅多に無いですが) 上限を指定することもあります。 ライブラリの依存関係は setup.py では install_requires で指定します。

ライブラリは究極的には、とある アプリケーション で使われるためのものです。 アプリケーションはそれとは違って、通常は他のプロジェクトから依存されることはありません。 アプリケーションは、ある特定の環境に配置され、依存関係やさらにその先の依存関係全ての正確なバージョンが具体的であるようになっています。 この処理をより簡単にすることが、現在Pipenvの最も重要な目標です。

まとめると次のようになります:

  • ライブラリは、 setup.pyinstall_requires抽象的な依存関係 を定義します。 厳密にどのバージョンをインストールし、どこから依存パッケージを取得するかの判断は、あなたが決めることではありません!
  • アプリケーションは、 Pipfile依存関係とそれをどこから取得するか を定義し、Pipfileを使って Pipfile.lock にある 具体的な依存関係 たちを更新します。 Pipfile.lockは、プロジェクトがきちんと動くことが分かっている特定の冪等な環境を定義します。 Pipfile.lock は正しさの源泉です。 Pipfile はそのlockファイルを作るのに便利なもので、実際に使う依存関係の正確なバージョンについて、曖昧なままにしておけます。 Pipenvは、きちんと動作する衝突の起きない依存関係のバージョン指定を定義する助けになります。他のツールではこの作業は非常にうんざりするものになります。
  • もちろん、 Pipfile とPipenvはライブラリの開発者にも便利なもので、開発環境やテスト環境を定義するのに使えます。
  • そして当り前ですが、ライブラリとアプリケーションの区別が明確でないプロジェクトもあります。 その場合は、Pipenvおよび Pipfile と一緒に install_requires を使ってください。

次のようにもできます:

$ pipenv install -e .

このコマンドでは、 setup.py で宣言されている依存関係を全てロックするようにPipenvに指示しています。

☤ Pipenvのキャッシュの場所を変更する

環境変数 PIPENV_CACHE_DIR を好きな場所に設定することで、デフォルトと異なるキャッシュの場所を使うようPipenvに強制できます。 これは PIP_CACHE_DIR を別のディレクトリに変更しているのと同じ状況で役に立ちます。

☤ Pythonのデフォルトバージョンを変更する

デフォルトでは、Pipenvはプロジェクトの初期化にpython3のどれかのバージョンを使います。 --three フラグもしくは --two フラグを付けてプロジェクトを始める他に、 --three--two を付けていないときには PIPENV_DEFAULT_PYTHON_VERSION を使ってプロジェクトを始めるときにどのバージョンを使うかを指定できます。

Pipenv CLI Reference

pipenv

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.

--completion

Output completion (to be eval'd).

--man

Display manpage.

--support

Output diagnostic information for use in GitHub issues.

--site-packages, --no-site-packages

Enable site-packages for the virtualenv.

--python <python>

Specify which version of Python virtualenv should use.

--three, --two

Use Python 3/2 when creating virtualenv.

--clear

Clears caches (pipenv, pip, and pip-tools).

-v, --verbose

Verbose mode.

--pypi-mirror <pypi_mirror>

Specify a PyPI mirror.

--version

Show the version and exit.

check

Checks for security vulnerabilities and against PEP 508 markers provided in Pipfile.

pipenv check [OPTIONS] [ARGS]...

Options

--unused <unused>

Given a code path, show potentially unused dependencies.

-i, --ignore <ignore>

Ignore specified vulnerability during safety checks.

--python <python>

Specify which version of Python virtualenv should use.

--three, --two

Use Python 3/2 when creating virtualenv.

--clear

Clears caches (pipenv, pip, and pip-tools).

-v, --verbose

Verbose mode.

--pypi-mirror <pypi_mirror>

Specify a PyPI mirror.

--system

System pip management.

Arguments

ARGS

Optional argument(s)

clean

Uninstalls all packages not specified in Pipfile.lock.

pipenv clean [OPTIONS]

Options

--bare

Minimal output.

--dry-run

Just output unneeded packages.

-v, --verbose

Verbose mode.

--three, --two

Use Python 3/2 when creating virtualenv.

--python <python>

Specify which version of Python virtualenv should use.

graph

Displays currently-installed dependency graph information.

pipenv graph [OPTIONS]

Options

--bare

Minimal output.

--json

Output JSON.

--json-tree

Output JSON in nested tree.

--reverse

Reversed dependency graph.

install

Installs provided packages and adds them to Pipfile, or (if no packages are given), installs all packages from Pipfile.

pipenv install [OPTIONS] [PACKAGES]...

Options

--system

System pip management.

-c, --code <code>

Install packages automatically discovered from import statements.

--deploy

Abort if the Pipfile.lock is out-of-date, or Python version is wrong.

--site-packages, --no-site-packages

Enable site-packages for the virtualenv.

--skip-lock

Skip locking mechanisms and use the Pipfile instead during operation.

-e, --editable <editable>

An editable python package URL or path, often to a VCS repo.

--ignore-pipfile

Ignore Pipfile when installing, using the Pipfile.lock.

--selective-upgrade

Update specified packages.

-r, --requirements <requirements>

Import a requirements.txt file.

--extra-index-url <extra_index_url>

URLs to the extra PyPI compatible indexes to query for package lookups.

-i, --index <index>

Target PyPI-compatible package index url.

--sequential

Install dependencies one-at-a-time, instead of concurrently.

--keep-outdated

Keep out-dated dependencies from being updated in Pipfile.lock.

--pre

Allow pre-releases.

-d, --dev

Install both develop and default packages.

--python <python>

Specify which version of Python virtualenv should use.

--three, --two

Use Python 3/2 when creating virtualenv.

--clear

Clears caches (pipenv, pip, and pip-tools).

-v, --verbose

Verbose mode.

--pypi-mirror <pypi_mirror>

Specify a PyPI mirror.

Arguments

PACKAGES

Optional argument(s)

Environment variables

PIPENV_SKIP_LOCK

Provide a default for --skip-lock

PIP_EXTRA_INDEX_URL

Provide a default for --extra-index-url

PIP_INDEX_URL

Provide a default for -i

lock

Generates Pipfile.lock.

pipenv lock [OPTIONS]

Options

-r, --requirements

Generate output in requirements.txt format.

--keep-outdated

Keep out-dated dependencies from being updated in Pipfile.lock.

--pre

Allow pre-releases.

-d, --dev

Install both develop and default packages.

--python <python>

Specify which version of Python virtualenv should use.

--three, --two

Use Python 3/2 when creating virtualenv.

--clear

Clears caches (pipenv, pip, and pip-tools).

-v, --verbose

Verbose mode.

--pypi-mirror <pypi_mirror>

Specify a PyPI mirror.

open

View a given module in your editor.

This uses the EDITOR environment variable. You can temporarily override it, for example:

EDITOR=atom pipenv open requests
pipenv open [OPTIONS] MODULE

Options

--python <python>

Specify which version of Python virtualenv should use.

--three, --two

Use Python 3/2 when creating virtualenv.

--clear

Clears caches (pipenv, pip, and pip-tools).

-v, --verbose

Verbose mode.

--pypi-mirror <pypi_mirror>

Specify a PyPI mirror.

Arguments

MODULE

Required argument

run

Spawns a command installed into the virtualenv.

pipenv run [OPTIONS] COMMAND [ARGS]...

Options

--python <python>

Specify which version of Python virtualenv should use.

--three, --two

Use Python 3/2 when creating virtualenv.

--clear

Clears caches (pipenv, pip, and pip-tools).

-v, --verbose

Verbose mode.

--pypi-mirror <pypi_mirror>

Specify a PyPI mirror.

Arguments

COMMAND

Required argument

ARGS

Optional argument(s)

shell

Spawns a shell within the virtualenv.

pipenv shell [OPTIONS] [SHELL_ARGS]...

Options

--fancy

Run in shell in fancy mode. Make sure the shell have no path manipulating scripts. Run $pipenv shell for issues with compatibility mode.

--anyway

Always spawn a subshell, even if one is already spawned.

--pypi-mirror <pypi_mirror>

Specify a PyPI mirror.

--three, --two

Use Python 3/2 when creating virtualenv.

--python <python>

Specify which version of Python virtualenv should use.

Arguments

SHELL_ARGS

Optional argument(s)

sync

Installs all packages specified in Pipfile.lock.

pipenv sync [OPTIONS]

Options

--bare

Minimal output.

--sequential

Install dependencies one-at-a-time, instead of concurrently.

--keep-outdated

Keep out-dated dependencies from being updated in Pipfile.lock.

--pre

Allow pre-releases.

-d, --dev

Install both develop and default packages.

--python <python>

Specify which version of Python virtualenv should use.

--three, --two

Use Python 3/2 when creating virtualenv.

--clear

Clears caches (pipenv, pip, and pip-tools).

-v, --verbose

Verbose mode.

--pypi-mirror <pypi_mirror>

Specify a PyPI mirror.

uninstall

Un-installs a provided package and removes it from Pipfile.

pipenv uninstall [OPTIONS] [PACKAGES]...

Options

--all-dev

Un-install all package from [dev-packages].

--all

Purge all package(s) from virtualenv. Does not edit Pipfile.

-e, --editable <editable>

An editable python package URL or path, often to a VCS repo.

--skip-lock

Skip locking mechanisms and use the Pipfile instead during operation.

--keep-outdated

Keep out-dated dependencies from being updated in Pipfile.lock.

--pre

Allow pre-releases.

-d, --dev

Install both develop and default packages.

--python <python>

Specify which version of Python virtualenv should use.

--three, --two

Use Python 3/2 when creating virtualenv.

--clear

Clears caches (pipenv, pip, and pip-tools).

-v, --verbose

Verbose mode.

--pypi-mirror <pypi_mirror>

Specify a PyPI mirror.

Arguments

PACKAGES

Optional argument(s)

Environment variables

PIPENV_SKIP_LOCK

Provide a default for --skip-lock

update

Runs lock, then sync.

pipenv update [OPTIONS] [PACKAGES]...

Options

--bare

Minimal output.

--outdated

List out-of-date dependencies.

--dry-run

List out-of-date dependencies.

-e, --editable <editable>

An editable python package URL or path, often to a VCS repo.

--ignore-pipfile

Ignore Pipfile when installing, using the Pipfile.lock.

--selective-upgrade

Update specified packages.

-r, --requirements <requirements>

Import a requirements.txt file.

--extra-index-url <extra_index_url>

URLs to the extra PyPI compatible indexes to query for package lookups.

-i, --index <index>

Target PyPI-compatible package index url.

--sequential

Install dependencies one-at-a-time, instead of concurrently.

--keep-outdated

Keep out-dated dependencies from being updated in Pipfile.lock.

--pre

Allow pre-releases.

-d, --dev

Install both develop and default packages.

--python <python>

Specify which version of Python virtualenv should use.

--three, --two

Use Python 3/2 when creating virtualenv.

--clear

Clears caches (pipenv, pip, and pip-tools).

-v, --verbose

Verbose mode.

--pypi-mirror <pypi_mirror>

Specify a PyPI mirror.

Arguments

PACKAGES

Optional argument(s)

Environment variables

PIP_EXTRA_INDEX_URL

Provide a default for --extra-index-url

PIP_INDEX_URL

Provide a default for -i

Pipenvでよく出喰わす問題

Pipenvはボランティアにより常に改善されていますが、現時点でも非常に幼いリソースの限られているプロジェクトで、対処する必要のあるゆがみもあります。 皆の援助が必要なのです (あなたの援助もです!)。

ここではPipenvを使っている人達が抱くことの多い疑問について解説します。 以下に書かれていることをよく読んで、あなたが遭遇している問題を解決できるかどうかを調べてください。

注釈

まず最初に、最新のPipenvが動いていることを確認してください!

☤ Your dependencies could not be resolved (依存関係が解決できない)

依存関係が 本当に 解決できることを確かめてください。 その確信が持てたのなら、依存関係解決のキャッシュをクリアする必要があるかもしれません。 次のコマンドを実行して:

pipenv lock --clear

再度試してみてください。

これで上手くいかない場合は、キャッシュディレクトリ全体を手作業で削除してみてください。 キャッシュディレクトリは通常は、次の場所のうちのどこかです:

  • ~/Library/Caches/pipenv (macOS)
  • %LOCALAPPDATA%\pipenv\pipenv\Cache (Windows)
  • ~/.cache/pipenv (それ以外のオペレーティングシステム)

Pipenvはデフォルトではプレリリース版 (例えば、alpha, betaなどの接尾語が 1.0b1 のように付いているバージョン) はインストールしません。 コマンドに --pre フラグを渡すか、次のような設定を

[pipenv]
allow_prereleases = true

Pipfileに書く必要があります。

☤ <モジュール名> というモジュールが無い

たいていはPipenvとシステムパッケージが混ざってしまっているのが原因です。 Pipenvは隔離された環境にインストールすることを 強く 推奨します。 既にインストールされているPipenvを全てアンインストールし、 ☤ Pipenvのインストール を参照して、推奨されている方法でPipenvをインストールしてください。

☤ pyenvでインストールしたPythonが見付からない

PYENV_ROOT が正しく設定されているか確認してください。 Pipenvは 3.6.4 やそれに類するバージョン名を持つCPythonディストリビューションのみサポートしています。

☤ PipenvがpyenvのglobalおよびlocalのPythonバージョンを考慮しない

Pipenvはデフォルトでは仮想環境を作成するのに使われたPythonを使います。 --python オプションを設定するか、もしくはインタプリタを選択するときに $PYENV_ROOT/shims/python を設定してpyenvを参照させられます。 より詳しいことは ☤ パッケージのバージョンを指定する を参照してください。

Pipenvが自動的に「ちゃんと動いて」欲しい場合は、環境変数 PIPENV_PYTHON$PYENV_ROOT/shims/python に設定して対応できます。 この設定によって、Pipenvは仮想環境を作成するために、デフォルトでpyenvのアクティブなPythonバージョンを使用します。

☤ ValueError: unknown locale: UTF-8 (未知のロケール: UTF-8)

macOSには、使っているシェルのエンコーディングを正しく判定できないというバグがあります。 また別のシステムでも、ロケール変数がエンコードの指定をしていない場合に問題になります。

ワークアラウンドは次の2つの環境変数に標準的なローカライズ形式を設定することです:

  • LC_ALL
  • LANG

Bashでは例えば、次の設定を ~/.bash_profile に追加できます:

export LC_ALL='en_US.UTF-8'
export LANG='en_US.UTF-8'

Zshでは、修正するファイルは ~/.zshrc です。

注釈

en_USUTF-8 の部分は両方とも、使用する言語とロケールおよびエンコーディングに変更できます。

☤ /bin/pip: No such file or directory (そのようなファイルまたはディレクトリはありません)

これはロケール設定が関係している可能性があります。 ☤ ValueError: unknown locale: UTF-8 (未知のロケール: UTF-8) を参照すると解決するかもしれません。

shell で仮想環境名がプロンプトに出ない

これは意図的なものです。 他のシェルプラグインを使ったり、 PS1 を設定するというより上手い方法を使って自力で実現できます。 どうしても仮想環境名を表示したければ、次のコマンドが使えます

pipenv shell -c

(ただしWindowsでは使えません)。

☤ Pipenvがsetup.pyにある依存関係を考慮しない

これは意図的に考慮していません。 Pipfileとsetup.pyはそれぞれ異なった目的にかなうもので、デフォルトではお互いを考慮しません。 より詳しいことは ☤ Pipfile vs setup.py を参照してください。

☤ supervisorプログラムで pipenv run を使う

supervisorプログラムの commandpipenv run ... を設定するときは、ローカル環境変数を適切に設定して、きちんと動くようにする必要があります。

次の行を /etc/supervisor/supervisord.conf[supervisord] セクションの下に追加してください:

[supervisord]
environment=LC_ALL='en_US.UTF-8',LANG='en_US.UTF-8'

Locking dependencies… となっている間に例外が送出される

pipenv lock --clear を実行してから、再度試してください。 ロック処理は、以後の実行を速くするために結果をキャッシュします。 バグがあってフォーマットが壊れてしまった場合、そのバグが修正された後でも、そのキャッシュに間違った結果が残っていることがあります。 --clear はそのキャッシュを捨てるので、不正な結果が取り除かれます。

貢献のためのガイド

Development Philosophy

Pipenv is an open but opinionated tool, created by an open but opinionated developer.

Management Style

To be updated (as of March 2020).

Kenneth Reitz is the BDFL. He has final say in any decision related to the Pipenv project. Kenneth is responsible for the direction and form of the library, as well as its presentation. In addition to making decisions based on technical merit, he is responsible for making decisions based on the development philosophy of Pipenv.

Dan Ryan, Tzu-ping Chung, and Nate Prewitt are the core contributors. They are responsible for triaging bug reports, reviewing pull requests and ensuring that Kenneth is kept up to speed with developments around the library. The day-to-day managing of the project is done by the core contributors. They are responsible for making judgements about whether or not a feature request is likely to be accepted by Kenneth.

Values

  • Simplicity is always better than functionality.
  • Listen to everyone, then disregard it.
  • The API is all that matters. Everything else is secondary.
  • Fit the 90% use-case. Ignore the nay-sayers.

Contributing to Pipenv

If you're reading this, you're probably interested in contributing to Pipenv. Thank you very much! Open source projects live-and-die based on the support they receive from others, and the fact that you're even considering contributing to the Pipenv project is very generous of you.

This document lays out guidelines and advice for contributing to this project. If you're thinking of contributing, please start by reading this document and getting a feel for how contributing to this project works. If you have any questions, feel free to reach out to either Dan Ryan, Tzu-ping Chung, or Nate Prewitt, the primary maintainers.

The guide is split into sections based on the type of contribution you're thinking of making, with a section that covers general guidelines for all contributors.

General Guidelines

Be Cordial
Be cordial or be on your way. —Kenneth Reitz

Pipenv has one very important rule governing all forms of contribution, including reporting bugs or requesting features. This golden rule is "be cordial or be on your way".

All contributions are welcome, as long as everyone involved is treated with respect.

Get Early Feedback

If you are contributing, do not feel the need to sit on your contribution until it is perfectly polished and complete. It helps everyone involved for you to seek feedback as early as you possibly can. Submitting an early, unfinished version of your contribution for feedback in no way prejudices your chances of getting that contribution accepted, and can save you from putting a lot of work into a contribution that is not suitable for the project.

Contribution Suitability

Our project maintainers have the last word on whether or not a contribution is suitable for Pipenv. All contributions will be considered carefully, but from time to time, contributions will be rejected because they do not suit the current goals or needs of the project.

If your contribution is rejected, don't despair! As long as you followed these guidelines, you will have a much better chance of getting your next contribution accepted.

Questions

The GitHub issue tracker is for bug reports and feature requests. Please do not use it to ask questions about how to use Pipenv. These questions should instead be directed to Stack Overflow. Make sure that your question is tagged with the pipenv tag when asking it on Stack Overflow, to ensure that it is answered promptly and accurately.

Code Contributions

Steps for Submitting Code

When contributing code, you'll want to follow this checklist:

  1. Understand our development philosophy.
  2. Fork the repository on GitHub.
  3. Set up your Development Setup
  4. Run the tests (Testing) to confirm they all pass on your system. If they don't, you'll need to investigate why they fail. If you're unable to diagnose this yourself, raise it as a bug report by following the guidelines in this document: Bug Reports.
  5. Write tests that demonstrate your bug or feature. Ensure that they fail.
  6. Make your change.
  7. Run the entire test suite again, confirming that all tests pass including the ones you just added.
  8. Send a GitHub Pull Request to the main repository's master branch. GitHub Pull Requests are the expected method of code collaboration on this project.

The following sub-sections go into more detail on some of the points above.

Development Setup

To get your development environment setup, run:

pip install -e .
pipenv install --dev

This will install the repo version of Pipenv and then install the development dependencies. Once that has completed, you can start developing.

The repo version of Pipenv must be installed over other global versions to resolve conflicts with the pipenv folder being implicitly added to sys.path. See pypa/pipenv#2557 for more details.

Testing

Tests are written in pytest style and can be run very simply:

pytest

This will run all Pipenv tests, which can take awhile. To run a subset of the tests, the standard pytest filters are available, such as:

  • provide a directory or file: pytest tests/unit or pytest tests/unit/test_cmdparse.py
  • provide a keyword expression: pytest -k test_lock_editable_vcs_without_install
  • provide a nodeid: pytest tests/unit/test_cmdparse.py::test_parse
  • provide a test marker: pytest -m lock
Code Review

Contributions will not be merged until they've been code reviewed. You should implement any code review feedback unless you strongly object to it. In the event that you object to the code review feedback, you should make your case clearly and calmly. If, after doing so, the feedback is judged to still apply, you must either apply the feedback or withdraw your contribution.

Package Index

To speed up testing, tests that rely on a package index for locking and installing use a local server that contains vendored packages in the tests/pypi directory. Each vendored package should have it's own folder containing the necessary releases. When adding a release for a package, it is easiest to use either the .tar.gz or universal wheels (ex: py2.py3-none). If a .tar.gz or universal wheel is not available, add wheels for all available architectures and platforms.

Documentation Contributions

Documentation improvements are always welcome! The documentation files live in the docs/ directory of the codebase. They're written in reStructuredText, and use Sphinx to generate the full suite of documentation.

When contributing documentation, please do your best to follow the style of the documentation files. This means a soft-limit of 79 characters wide in your text files and a semi-formal, yet friendly and approachable, prose style.

When presenting Python code, use single-quoted strings ('hello' instead of "hello").

Bug Reports

Bug reports are hugely important! They are recorded as GitHub issues. Please be aware of the following things when filing bug reports:

  1. Avoid raising duplicate issues. Please use the GitHub issue search feature to check whether your bug report or feature request has been mentioned in the past. Duplicate bug reports and feature requests are a huge maintenance burden on the limited resources of the project. If it is clear from your report that you would have struggled to find the original, that's ok, but if searching for a selection of words in your issue title would have found the duplicate then the issue will likely be closed extremely abruptly.

  2. When filing bug reports about exceptions or tracebacks, please include the complete traceback. Partial tracebacks, or just the exception text, are not helpful. Issues that do not contain complete tracebacks may be closed without warning.

  3. Make sure you provide a suitable amount of information to work with. This means you should provide:

    • Guidance on how to reproduce the issue. Ideally, this should be a small code sample that can be run immediately by the maintainers. Failing that, let us know what you're doing, how often it happens, what environment you're using, etc. Be thorough: it prevents us needing to ask further questions.
    • Tell us what you expected to happen. When we run your example code, what are we expecting to happen? What does "success" look like for your code?
    • Tell us what actually happens. It's not helpful for you to say "it doesn't work" or "it fails". Tell us how it fails: do you get an exception? A hang? The packages installed seem incorrect? How was the actual result different from your expected result?
    • Tell us what version of Pipenv you're using, and how you installed it. Different versions of Pipenv behave differently and have different bugs, and some distributors of Pipenv ship patches on top of the code we supply.

    If you do not provide all of these things, it will take us much longer to fix your problem. If we ask you to clarify these and you never respond, we will close your issue without fixing it.

Run the tests

Three ways of running the tests are as follows:

  1. make test (which uses docker)
  2. ./run-tests.sh or run-tests.bat
  3. Using pipenv:
$ git clone https://github.com/pypa/pipenv.git
$ cd pipenv
$ git submodule sync && git submodule update --init --recursive
$ pipenv install --dev
$ pipenv run pytest

For the last two, it is important that your environment is setup correctly, and this may take some work, for example, on a specific Mac installation, the following steps may be needed:

# Make sure the tests can access github
if [ "$SSH_AGENT_PID" = "" ]
then
   eval `ssh-agent`
   ssh-add
fi

# Use unix like utilities, installed with brew,
# e.g. brew install coreutils
for d in /usr/local/opt/*/libexec/gnubin /usr/local/opt/python/libexec/bin
do
  [[ ":$PATH:" != *":$d:"* ]] && PATH="$d:${PATH}"
done

export PATH

# PIP_FIND_LINKS currently breaks test_uninstall.py
unset PIP_FIND_LINKS