Skip to content

Instantly share code, notes, and snippets.

@metaist
Last active September 2, 2015 18:50
Show Gist options
  • Save metaist/4c97389d5b3fe797f78e to your computer and use it in GitHub Desktop.
Save metaist/4c97389d5b3fe797f78e to your computer and use it in GitHub Desktop.
Better virtualenv activate.
# Show virtual environment (if any) and git branch (if any; requires .git-prompt.sh).
source ~/.git-prompt.sh
__blank="\[\e]0;\w\a\]\n" # white
__virtualenv=`basename "$VIRTUAL_ENV"`
__userhost="\[\e[32m\]\u@\h" # green
__pwd="\[\e[33m\]\w" # yellow
__cursor="\[\e[0m\]\n\$ " # white
export PS1="${__blank}${__virtualenv:+$__virtualenv }${__userhost} ${__pwd}\$(__git_ps1)${__cursor}"

Install

  1. Copy inve and inve.bat (for Windows) into a destination on your $PATH.
  2. Append .bashrc to your ~/.bashrc.

Usage

virtualenv [env]
inve [env]

env - name of the virtualenv environment (default: .env)

Motivation

I was persuaded by Michael Lamb's gist Virtualenv's bin/activate is Doing It Wrong and I decided to implement most of his suggestsions with a few simplifications and extensions.

Notably, I assumed a default virtual environment called .env so that I can just write inve (similar to workon from virtualenvwrapper).

#!/bin/sh
__venv=".env"
if [ "$1" ]; then
__venv="$1"
shift
fi
if [ -d "$PWD/${__venv}" ]; then
echo "loading virtualenv ${__venv}"
export VIRTUAL_ENV="$PWD/${__venv}"
export PATH="$VIRTUAL_ENV/bin:$PATH"
unset PYTHONHOME
exec "${@:-$SHELL}"
else
echo "no virtualenv named ${__venv}"
echo "try: virtualenv ${__venv}"
fi
@echo off
setlocal
if "%1"=="" (set "VENV=.env") else (set "VENV=%1")
if EXIST "%CD%\%VENV%" (goto load) else (goto err)
:load
echo loading virtualenv %VENV%
cmd /V:ON /K "set "VIRTUAL_ENV=%CD%\%VENV%\" & set "PATH=%CD%\%VENV%\Scripts;%PATH%" & set "PROMPT=%VENV% %PROMPT%" & set "PYTHONHOME=""
goto end
:err
echo no virtualenv named %VENV%
echo try: virtualenv %VENV%
echo.
:end
@metaist
Copy link
Author

metaist commented Sep 2, 2015

Revision 4

  • Add: error handling for trying to load a virtual environment that doesn't exist.
  • Add: console messages

@metaist
Copy link
Author

metaist commented Sep 2, 2015

Revision 5

  • Fix: update branch name when switching branches

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment