Integrating direnv with python-build

30 Jan 2019 17:25 direnv python

To integrate direnv with python-build – installation instructions here – add the following to ~/.direnvrc:

use_python() {

    if [ -s "$PYTHON_PREFIX" ]; then
        load_prefix "$PYTHON_PREFIX"
        tput setaf 1
        echo "Python $PYTHON_VERSION not available; using default"
        echo "See"
        tput sgr0

Then add (e.g.) the following to your project’s .envrc:

use python 2.7.15
layout python

Important: Make sure you’ve installed virtualenv, outside any virtualenv:

$(/usr/bin/python -m site --user-base)/bin/pip install --user virtualenv

The $(...) bit is to escape from your virtualenv, if you’re already in one. (h/t)

The layout python takes care of setting up a Python virtualenv for you.

If you’re using a requirements.txt file to track your Python requirements, you might want to add the following:

# We have no way to do this automatically, so hint, rather than assert.
if [ -f requirements.txt ]; then
    tput setaf 3
    echo "(Maybe) Install missing python packages with 'pip install -r requirements.txt'"
    tput sgr0

Note that I find requirements.txt to be a bit parochial, so at Electric Imp, we use python_requirements.txt.