Pipenvの進んだ使い方¶

このドキュメントではPipenvのより輝かしい進んだ機能を対象としています。
☤ 注意書き¶
Pipfile
にある依存パッケージのwheelは$pipenvlock
では捕捉されません。- 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=truename="pypi"[[source]]url="http://pypi.home.kennethreitz.org/simple"verify_ssl=falsename="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=truename="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 aValueError,"Noclosingquotation"
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=truename="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
注釈
pipenvinstall--ignore-pipfile
is nearly equivalent topipenvsync
, butpipenvsync
willnever attempt to re-lock your dependencies as it is considered an atomic operation.pipenvinstall
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
の生成¶
Pipfile
やPipfile.lock
はrequirements.txt
に非常に簡単に変換でき、追加機能や素敵な機能など既に実装された機能全ての恩恵を受けられます。
このPipfile
から:
[[source]]url="https://pypi.python.org/simple"verify_ssl=true[packages]requests={version="*"}
requirements.txt
を生成しましょう:
$ pipenv lock -rchardet==3.0.4requests==2.18.4certifi==2017.7.27.1idna==2.6urllib3==1.22
開発用の依存関係だけのrequirements.txt
を生成したいと思った場合は、それも可能です!次のPipfile
を用意しましょう:
[[source]]url="https://pypi.python.org/simple"verify_ssl=true[dev-packages]pytest={version="*"}
requirements.txt
を生成しましょう:
$ pipenv lock -r --devpy==1.4.34pytest==3.2.3
めっちゃ高機能。
☤ セキュリティの脆弱性の検知¶
Pipenv はsafety パッケージを含んでいて、既知のセキュリティの脆弱性が無いか依存関係グラフを走査するのに使われます。
例:
$ cat Pipfile[packages]django = "==1.10.1"$ pipenv checkChecking 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 theseredirects (namely ``django.utils.http.is_safe_url()``) considered some numericURLs (e.g. ``http:999999999``) "safe" when they shouldn't be.Also, if a developer relies on ``is_safe_url()`` to provide safe redirecttargets 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. Theview no longer does any redirects as they don't provide any known, usefulfunctionality.Note, however, that this view has always carried a warning that it is nothardened for production use and should be used only as a development aid.
✨🍰✨
注釈
In order to enable this functionality while maintaining its permissivecopyright license,pipenv embeds an API client key for the backendSafety API operated by pyup.io rather than including a full copy of theCC-BY-NC-SA licensed Safety-DB database. This embedded client key isshared across allpipenv check users, and hence will be subject toAPI access throttling based on overall usage rather than individualclient usage.
You can also use your own safety API key by setting theenvironment variablePIPENV_PYUP_API_KEY
.
☤ コミュニティとの連係¶
Pipenvと連係する様々なプロダクトに加え、コミュニティがメンテナンスしている多種多様のプラグインや拡張があり、様々なエディタやIDEで使えます:
- Heroku (クラウドホスティング)
- Platform.sh (クラウドホスティング)
- PyUp (セキュリティ通知)
- Emacs (エディタ連係)
- Fish Shell (自動
$pipenvshell
!) - VS Code (エディタ連係)
- PyCharm (エディタ連係)
対応中:
- Sublime Text (エディタ連係)
- 未だその姿を見せていない来たるべきGoogle Cloudプロダクト (クラウドホスティング)
☤ エディタでモジュールを開く¶
Pipenvを使うと$pipenvopen
コマンドで、(自分で書いたコードベースを含め) インストールされているどんなPythonモジュールも開けます:
$ pipenv install -e git+https://github.com/kennethreitz/background.git#egg=backgroundInstalling -e git+https://github.com/kennethreitz/background.git#egg=background…...Updated Pipfile.lock!$ pipenv open backgroundOpening '/Users/kennethreitz/.local/share/virtualenvs/hmm-mGOawwm_/src/background/background.py' in your EDITOR.
この機能のおかげで、GitHubまで見に行かなくても、今使っているコードを手軽に読めるようになります。
注釈
この機能では標準のEDITOR
環境変数が使われます。例えばVS Codeを使っている場合は、exportEDITOR=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 installWarning: Python 3.6 was not found on your system…Would you like us to install latest CPython 3.6 with pyenv? [Y/n]: yInstalling 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:03To activate this project's virtualenv, run the following: $ pipenv shell
Pipenv はPEP 508 が規定するpython_full_version
とpython_version
の両方に従います。
💫✨🍰✨💫
☤.env
の自動読み込み¶
プロジェクトに.env
ファイルが存在する場合は、$pipenvshell
および$pipenvrun
は自動で読み込みます:
$ cat .envHELLO=WORLD⏎$ pipenv run pythonLoading .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 darwinType "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 .envCONFIG_PATH=${HOME}/.config/foo$ pipenv run pythonLoading .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 linuxType "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
Seetheskumar/python-dotenv for more information on.env
files.
☤ 独自のスクリプトショートカット¶
Pipenvは、Pipfileのオプションの[scripts]
節で独自のショートカットの作成をサポートしています。
そのショートカットは、ターミナルでpipenvrun<shortcutname>
と実行でき、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 printspamI 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 fragmentsin 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 = truename = "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 usewhatever Python Pipenv is installed under (i.e.sys.executable
). Commandline flags (e.g.--python
,--three
, and--two
) are prioritized overthis 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
= ''¶設定された場合、ターミナルエミュレーターの名前に
pipenvshell
が使われます。デフォルトでは、エミュレーターを自動的に検出します。例えば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 CIenvironments.
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 thePipfile is located, instruct pipenv to find the Pipfile in the locationspecified 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 newapproach, you may set this to '0', 'off', or 'false'.
pipenv.environments.
PIPENV_SHELL
= None¶An absolute path to the preferred shell for
pipenvshell
.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
pipenvshell
.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
anduninstall
commands.
pipenv.environments.
PIPENV_SPINNER
= 'dots'¶Sets the default spinner type.
Spinners are identitcal to the node.js spinners and can be found athttps://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 sessionif 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 theWORKON_HOME
environment variable, if youhave it set — so you can tell pipenv to store your virtual environmentswherever you want, e.g.:
exportWORKON_HOME=~/.venvs
さらに、PIPENV_VENV_IN_PROJECT
環境変数を設定することで、project/.venv
にある仮想環境をPipenvに使わせることができます。
☤ プロジェクトのテスト¶
PipenvはRequests のようなプロジェクトで開発用の依存関係の宣言とテストスイートの実行に使われています。
現時点ではTravis-CI とtox の両方で上手くデプロイのテストを行えています。
Travis CI¶
Travis CIの設定例はRequests にあります。このプロジェクトではMakefileによく使う関数をinit
コマンドやtests
コマンドとして定義してあります。以下が.travis.yml
の本質的なところを抜き出したものです:
language:pythonpython:-"2.6"-"2.7"-"3.3"-"3.4"-"3.5"-"3.6"-"3.7-dev"# command to install dependenciesinstall:"make"# command to run testsscript:-maketest
そして対応するMakefileは以下の通りです:
init:pipinstallpipenvpipenvinstall--devtest:pipenvrunpytesttests
ToX自動化プロジェクト¶
または、tox.ini
を次のようにローカル環境でのテストと外部環境でのテストの両方に対して設定できます:
[tox]envlist=flake8-py3,py26,py27,py33,py34,py35,py36,pypy[testenv]deps=pipenvcommands=pipenvinstall--devpipenvrunpytesttests[testenv:flake8-py3]basepython=python3.4commands=pipenvinstall--devpipenvrunflake8--versionpipenvrunflake8setup.pydocsprojecttest
Pipenv will automatically use the virtualenv provided bytox
. Ifpipenvinstall--dev
installs e.g.pytest
, then installed commandpytest
will be present in given virtualenv and can be called directly bypytesttests
instead ofpipenvrunpytesttests
.
テストを実行するたびにうっかりlockファイルを編集してしまわないように、pipenvinstall
に--ignore-pipfile
を付けたいと思うかもしれません。これをするとPipenvがPipfile
への変更を無視してしまうのと、(もっと重要なこととして) 現在の環境をPipfile.lock
に追加するのを防ぎます。これが重要な点なのは、今いる環境 (すなわちtoxが用意した仮想環境) は通常は (望ましいもしくは望しくないことに) 現時点のプロジェクトと、tox
のdeps
に設定されている追加の依存関係を含んでいるためです。最初に用意される環境に対しては、この方法ではなく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.py
のinstall_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
を使ってプロジェクトを始めるときにどのバージョンを使うかを指定できます。