Bash script for locating nearest virtualenv directory #554

Open
mzuther opened this Issue Jan 26, 2014 · 2 comments

Projects

None yet

3 participants

@mzuther
mzuther commented Jan 26, 2014

Hi!

I really like virtualenv and have come up with a Bash script that - when placed in ~/.bash_aliases or so - moves up the path until it finds a virtualenv directory. If this doesn't fail, the script will source the "activate" script and print a message.

I find the script really handy, so feel free to include it in your documentation (or source) under any free software or documentation license you like... :)

Best regards,

Martin

function start_virtualenv()
{
    local VIRTUALENV_DIRECTORY=".venv"
    local PATH_TO_VIRTUALENV=$(pwd)

    # move up the path tree, but stop at root node
    while [ "$PATH_TO_VIRTUALENV" != '/' ]
    do
        # is virtualenv's "activate" script accessible from current
        # directory?
        if [ -r "$PATH_TO_VIRTUALENV/$VIRTUALENV_DIRECTORY/bin/activate" ]
        then
            echo
            echo "  Starting virtual environment:"
            echo "  $PATH_TO_VIRTUALENV"
            echo
            echo '  Exit with "deactivate".'
            echo

            # run "activate" script
            source "$PATH_TO_VIRTUALENV/$VIRTUALENV_DIRECTORY/bin/activate"

            # signal success
            return 0
        fi

        # move up the path to parent directory
        PATH_TO_VIRTUALENV=$(dirname "$PATH_TO_VIRTUALENV")
    done

    # signal failure
    return 1
}

# create a shortcut via alias
alias activate='start_virtualenv'
@erning
erning commented Feb 19, 2014

I have a similar helper tool that will execute commands just under current virtualenv https://github.com/erning/ve

@piotr-dobrogost

I use this

activate_virtualenv() {
    dir=`pwd`
    while [[ ! -f $dir/venv/bin/activate && -n $dir ]]; do
        dir=${dir%/*}
    done
    if [[ -f $dir/venv/bin/activate ]]; then
        echo "Activating virtualenv from $dir/venv"
        source $dir/venv/bin/activate
    else
        echo 'Virtualenv not found'
    fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment