Permalink
Browse files

Adding virtualenv_wrapper helper script.

Adding has_virtualenv function which will look for a .venv file in the
directory. If it exists, it will attempt to `workon` the project whose
name is written in the file.

For instance, if my .venv file contains the text:

oebfare

It will attempt to `workon oebfare`. As there shouldn't be a .venv
file in a directory that doesn't have a virtual env, there is no error
handling. This should be fixed.
  • Loading branch information...
1 parent a98ae22 commit 04899f005397499e89da6d562b062545e70d7975 @justinabrahms committed Mar 29, 2009
Showing with 9 additions and 0 deletions.
  1. +9 −0 .bash_profile
View
@@ -222,6 +222,15 @@ PS1="${RED}:${NORMAL}\@${RED}: ${CYAN}(${NORMAL}\w${CYAN})${GREEN} \$(parse_svn_
source $HOME/bin/virtualenvwrapper_bashrc
+has_virtualenv() {
+ if [ -e .venv ]; then
+ workon `cat .venv`
+ fi
+}
+venv_cd () {
+ cd "$@" && has_virtualenv
@dorkitude
dorkitude Jul 2, 2012

This is dangerous because, if you put this in your bashrc and source it more than once, it'll create an infinite loop -- alias cd will call a function that hits the alias cd.

I fixed this by using:

builtin cd inside the venv_cd function

@cjerdonek
cjerdonek Nov 19, 2013

I created a gist for this snippet here with @dorkitude's suggested change and some other minor modifications.

@bsgreenb
bsgreenb May 9, 2014

What up @dorkitude great minds think alike

@scharron
scharron Sep 24, 2014

To avoid messing with builtins, you can also use the PROMPT_COMMAND from bash.

PROMPT_COMMAND='prompt'

function prompt()
{
  if [ "$PWD" != "$MYOLDPWD" ]; then
    MYOLDPWD="$PWD"
    test -e .venv && workon `cat .venv`
  fi
}
@jessedhillon
jessedhillon Mar 22, 2015

@scharron has the right answer. The current script won't work with popd and pushd.

@justinabrahms
justinabrahms May 18, 2015 Owner

Thanks guys. I added a note in the original post with thank yous. Thank you all!

New source:
https://justin.abrah.ms/dotfiles/zsh.html#sec-2-7

@cjerdonek
cjerdonek Dec 23, 2015

FYI, if you haven't yet, I would take a look at pyenv / pyenv-virtualenv. It supersedes the need for doing this by automatically checking for a .python-version file. I've been really happy with it.

@afeld
afeld Sep 19, 2016 edited

I went a step further than @scharron's suggestion, and made a script that assumes you will want a virtual environment anytime you are in a directory with a requirements.txt file.

https://gist.github.com/afeld/4aefc7c9493f1519e141f52b40dc6479

Would love feedback!

+}
+alias cd="venv_cd"
# Welcome Message
echo -e ""

1 comment on commit 04899f0

@cjerdonek

Also, so that you don't override Mac OS X's behavior of preserving the current working directory when opening a new terminal window (or any other existing prompt behavior), it looks like you want to replace:

PROMPT_COMMAND='prompt'

with:

export PROMPT_COMMAND="${PROMPT_COMMAND};prompt"
Please sign in to comment.