Skip to content

Run pipenv shell automatically

Tzu-ping Chung edited this page Apr 25, 2018 · 7 revisions

Note: pipenv run should cover most use cases, and has the extra benefit of being able to run commands pre-scripted in Pipfile. It is recommended in general. For those preferring pipenv shell, however, the following tricks should be useful.

Bash

By @joapo:

# Activate current folder's pipenv virtualenv
# or accept an explicit virtualenv name
workon() {
    if [ $# -eq 0 ]
    then
        source $(pipenv --venv)/bin/activate
    else
        source ~/.virtualenvs/$1/bin/activate
    fi
}

# Making virtualenv alias
mkvenv() {
    cd ~/.virtualenvs
    virtualenv "$@"
    cd -
    workon "$1"
}

# Automatic virtualenv sourcing
function auto_pipenv_shell {
    if [ ! -n "$VIRTUAL_ENV" ]; then
        if [ -f "Pipfile" ] ; then
            workon
        fi
    fi
}
function cd {
    builtin cd "$@"
    auto_pipenv_shell
}
auto_pipenv_shell

A bare-bone version (only invoking pipenv shell on cd) by @Blue-Dog-Archolite:

function cd {
    builtin cd "$@"
    if [ -f "Pipfile" ] ; then
        pipenv shell
    fi
}

ZSH

By @caioariede:

function auto_pipenv_shell {
    if [ ! -n "${PIPENV_ACTIVE+1}" ]; then
        if [ -f "Pipfile" ] ; then
            pipenv shell
        fi
    fi
}

function cd {
    builtin cd "$@"
    auto_pipenv_shell
}

auto_pipenv_shell

Fish

Plugin fisherman/pipenv by @kennethreitz.

Clone this wiki locally