Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
# Installation:
# Add this line to your .bashrc or .bash-profile:
# source /path/to/
# 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\"...
source .venv/bin/activate
export PS1
export PROMPT_COMMAND=_virtualenv_auto_activate
Copy link

cwells commented Apr 20, 2013

You should probably verify that the .venv file is owned by the current user and has safe permissions (e.g. 0600). I'd also disallow root from doing this. Otherwise, this is known as a big security hole (cd into a dir and execute random hidden source file).

You could also restrict execution to subdirectories of the user's home dir.

But still, a nice snippet, thanks.

Copy link

cwells commented Apr 20, 2013

Adding this would probably be sufficient:

# only execute if .venv is owned by user and has safe permissions
if [ `stat -c "%a %u" .venv` = `echo 0600\`id -u\`` ]; then

Copy link

hfeeki commented Jun 2, 2013

if [ `stat -c "%u" .venv` = `id -u` ]; then

above code can works in my mac

Copy link

This actually works pretty well. The only issue I've run into is that you can not 'deactivate' the virtual environment unless you go outside of the directory. I wonder if there is a way to deactivate it at any level?

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 :

Copy link

Sashkow commented Feb 12, 2015

where should I put this script?

Copy link

Copy link

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

Copy link

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

Copy link

fmoor commented Jul 1, 2018

Copy link

tony commented Oct 28, 2022

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

Copy link

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