Skip to content

Instantly share code, notes, and snippets.

@codysoyland
Created March 25, 2012 18:34
Show Gist options
  • Star 74 You must be signed in to star a gist
  • Fork 25 You must be signed in to fork a gist
  • Save codysoyland/2198913 to your computer and use it in GitHub Desktop.
Save codysoyland/2198913 to your computer and use it in GitHub Desktop.
virtualenv-auto-activate
#!/bin/bash
# virtualenv-auto-activate.sh
#
# Installation:
# Add this line to your .bashrc or .bash-profile:
#
# source /path/to/virtualenv-auto-activate.sh
#
# Go to your project folder, run "virtualenv .venv", so your project folder
# has a .venv folder at the top level, next to your version control directory.
# For example:
# .
# ├── .git
# │   ├── HEAD
# │   ├── config
# │   ├── description
# │   ├── hooks
# │   ├── info
# │   ├── objects
# │   └── refs
# └── .venv
# ├── bin
# ├── include
# └── lib
#
# The virtualenv will be activated automatically when you enter the directory.
_virtualenv_auto_activate() {
if [ -e ".venv" ]; then
# Check to see if already activated to avoid redundant activating
if [ "$VIRTUAL_ENV" != "$(pwd -P)/.venv" ]; then
_VENV_NAME=$(basename `pwd`)
echo Activating virtualenv \"$_VENV_NAME\"...
VIRTUAL_ENV_DISABLE_PROMPT=1
source .venv/bin/activate
_OLD_VIRTUAL_PS1="$PS1"
PS1="($_VENV_NAME)$PS1"
export PS1
fi
fi
}
export PROMPT_COMMAND=_virtualenv_auto_activate
@brianpkennedy
Copy link

I was looking for something just like this, however to play nice with other PROMPT_COMMANDs it should end with

PROMPT_COMMAND="_virtualenv_auto_activate; $PROMPT_COMMAND"

I also had to do a fix for .venv symlinks, as I prefer to have one directory.

Forked here : https://gist.github.com/brianpkennedy/8943902

@Sashkow
Copy link

Sashkow commented Feb 12, 2015

where should I put this script?

@felippemr
Copy link

@markph0204
Copy link

I've head varying results with autoenv, try direnv for reliable results.

@amalsalim
Copy link

i didn't know about PROMPT_COMMAND. thank you very much!

@fmoor
Copy link

fmoor commented Jul 1, 2018

@tony
Copy link

tony commented Oct 28, 2022

@codysoyland are you okay releasing this under MIT license? ISC?

@codysoyland
Copy link
Author

codysoyland commented Oct 28, 2022

@codysoyland are you okay releasing this under MIT license? ISC?

You and anyone may use this for any purpose, no attribution needed.

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