Index ¦ Archives ¦ Atom

Virtualenv with Fish

Virtualenv is an awesome tool for managing python environments. Sadly enough it does not work so well with Fish out of the box. Based on http://coderseye.com/2010/using-virtualenv-with-fish-shell.html, I got a thin wrapper working for Fish:

 1  function mkvirtualenv -d "Create a new virtual environment in $WORKON\_HOME"
 2    set tgt {$WORKON\_HOME}$argv[1]
 3    if [ -d $tgt ]
 4      echo "$tgt exists already"
 5    else
 6      pushd $WORKON\_HOME
 7      virtualenv --distribute $argv[1]
 8      popd
 9    end
10  end
11 
12  function workon -d "Activate virtual environment in $WORKON\_HOME"
13    set tgt {$WORKON\_HOME}$argv[1]
14    if [ -d $tgt ]
15      pushd $tgt
16      deactivate
17      set -gx VIRTUAL\_ENV "$tgt"
18      set -gx \_OLD\_VIRTUAL\_PATH $PATH
19      set -gx PATH "$VIRTUAL\_ENV/bin" $PATH
20 
21      # unset PYTHONHOME if set
22      if set -q PYTHONHOME
23         set -gx \_OLD\_VIRTUAL\_PYTHONHOME $PYTHONHOME
24         set -e PYTHONHOME
25      end
26      popd
27    else
28      echo "$tgt not found"
29    end
30  end
31 
32  complete -c workon -a "(cd $WORKON\_HOME; ls -d \*)"
33 
34  function deactivate -d "Exit virtualenv and return to normal shell environment"
35      # reset old environment variables
36      if test -n "$\_OLD\_VIRTUAL\_PATH"
37          set -gx PATH $\_OLD\_VIRTUAL\_PATH
38          set -e \_OLD\_VIRTUAL\_PATH
39      end
40 
41      if test -n "$\_OLD\_VIRTUAL\_PYTHONHOME"
42          set -gx PYTHONHOME $\_OLD\_VIRTUAL\_PYTHONHOME
43          set -e \_OLD\_VIRTUAL\_PYTHONHOME
44      end
45      set -e VIRTUAL\_ENV
46  end

For the prompt I am using the following code

1  if set -q VIRTUAL\_ENV
2      printf '%s[%s]%s %s %s%s%s> ' (set\_color -b blue white) (basename "$VIRTUAL\_ENV") (set\_color normal) $USER "$\_\_fish\_prompt\_cwd" (prompt\_pwd) "$\_\_fish\_prompt\_normal"
3  else
4      printf '%s %s%s%s> ' $USER "$\_\_fish\_prompt\_cwd" (prompt\_pwd) "$\_\_fish\_prompt\_normal"
5  end

Which adds a prefix to my prompt when I have activated an environment.