Skip to content

Run pipenv shell automatically

Tzu-ping Chung edited this page Jul 24, 2020 · 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.

By @nicopauss. Should work in all POSIX shells. Unlike pipenv shell, the virtual environment is directly loaded in the current environment and thus it will not start a new sub-shell when the virtual environment is activated.

Similar to pipenv run or pipenv shell, when a .env is present, it will be loaded when the virtual environment is activated.

Bash

By @joaqo:

# 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

By @ethanj. Might work with Bash as well.

# automatically run "pipenv shell" if we enter a pipenv project subdirectory
# if opening a new terminal, preserve the source directory
PROMPT_COMMAND='prompt'
precmd() { eval "$PROMPT_COMMAND" }
function prompt()
{
    if [ ! $PIPENV_ACTIVE ]; then
      if [ `pipenv --venv 2>/dev/null` ]; then
        export PIPENV_INITPWD="$PWD"
        pipenv shell
      fi
    elif [ $PIPENV_INITPWD ] ; then
      cd "$PIPENV_INITPWD"
      unset PIPENV_INITPWD
    fi
}

Fish

Plugin fisherman/pipenv by @kennethreitz.

Clone this wiki locally