tail -f /dev/null

If you haven't had any obstacles lately, you're not challenging. be the worst.

PipenvでPythonの仮想環境を作る

Environment

pipenv --version
pipenv, version 2018.11.26

Install

option

virtualenv, virtualenvwrapper が既に install されている場合は削除.

brew uninstall pyenv-virtualenv
pip uninstall package virtualenvwrapper

pipenvのinstall。

pip install pipenv

環境変数の設定

.zshrc (.bashrc) に次を設定. PIPENV_VENV_IN_PROJECT を指定し project 直下に仮想環境を作成出来るようにする.

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

# Python
export PATH="/usr/local/opt/python/libexec/bin:$PATH"
export PIPENV_VENV_IN_PROJECT=true # pipenv packages will be stored inside the project.

仮想環境の作成

cd /path/to/project
pipenv --three
Using /usr/local/opt/python/libexec/bin/python (3.7.4) to create virtualenv…
✔ Successfully created virtual environment!
Virtualenv location: /Users/user/.local/share/virtualenvs/x

# specify version 3.7
pipenv --python 3.7

pip packageのinstall

pipenv install requests
Installing requests…
Adding requests to Pipfile's [packages]…
✔ Installation Succeeded

# install from requirements.txt
pipenv install -r ./requirements.txt

開発環境のみ利用する package 群を install する場合は以下.

pipenv install --dev requests

pipenvでinstallしたpackageの確認。

pipenv graph
requests==2.22.0
  - certifi [required: >=2017.4.17, installed: 2019.9.11]
  - chardet [required: >=3.0.2,<3.1.0, installed: 3.0.4]
  - idna [required: >=2.5,<2.9, installed: 2.8]
  - urllib3 [required: >=1.21.1,<1.26,!=1.25.1,!=1.25.0, installed: 1.25.3]

install した package の脆弱性を確認する場合は check command を利用する.

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

仮想環境で subshell を起動し仮想環境内に入る

pipenv shell
Launching subshell in virtual environment…
 . /Users/user/.local/share/virtualenvs/user/bin/activate

仮想環境の restore

Pipfile から restore することが出来る.

pipenv install

# install packages for dev env
pipenv install --dev

Pipfile.lock から restore することも出来る.

pipenv sync
pipenv sync --dev

Custom script shortcuts

Pipenvに [scripts] を定義し、カスタムショートカットを定義することが出来る.

pipenv run <shortcut>

詳しくは https://docs.pipenv.org/en/latest/advanced/#custom-script-shortcuts を参照.

仮想環境の削除

pipenv --rm

Trouble shooting

deactivate後、再度activate出来ない

subshellを抜ける為には deactivate ではなく、sessionを exit 等で閉じる必要がある.

pipenv shell
Shell for UNKNOWN_VIRTUAL_ENVIRONMENT already activated.
No action taken to avoid nested environments.

exit
pipenv shell

Pythonをバージョン指定してインストール出来ない

pipenv --python 3.6.4

Warning: Python 3.6.4 was not found on your system…
You can specify specific versions of Python with:
  $ pipenv --python path/to/python

入れたい version を pyenv で install し, PATH を指定して再度仮想環境を作成する.

pyenv install 3.6.4
pyenv local 3.6.4

pipenv --python /Users/user/.pyenv/versions/3.6.4/bin/python3.6 shell
Using /Users/user/.pyenv/versions/3.6.4/bin/python3.6 (3.6.4) to create virtualenv…
⠦ Creating virtual environment...Already using interpreter /Users/user/.pyenv/versions/3.6.4/bin/python3.6

以下, 同じような事象 (WSL)