如何编辑.bashrc以使用virtualenvwrapper的workon命令

时间:2014-10-30 16:53:29

标签: python virtualenv

每次打开终端我都要运行此命令

source $(which virtualenvwrapper.sh)

使用

workon myenv

我想知道我需要添加到.bashrc中,以便我可以立即使用workon命令, 在

之前不使用source

我正在使用Ubuntu 14.04

3 个答案:

答案 0 :(得分:9)

根据virtualenvwrapper docs,您可以将以下内容添加到.bashrc

export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh

我个人喜欢lazy loading option因为它可以快速保持shell启动速度。

答案 1 :(得分:2)

我在.bash_profile中有这个帮助在虚拟环境之间移动。它包含了每次都不需要获取shell脚本所需的信息,但它还包括一种自动“工作”的方法。进入目录时的环境。

如果你只有一个,我不确定我是否看到了virtualenvs的观点。

export WORKON_HOME=~/.virtualenvs
export PROJECT_HOME=~/Development/python
export VIRTUALENVWRAPPER_PYTHON=/usr/local/bin/python3
source /usr/local/bin/virtualenvwrapper.sh

# Call virtualenvwrapper's "workon" if .venv exists.
# Source: https://gist.github.com/clneagu/7990272
# This is modified from--
# https://gist.github.com/cjerdonek/7583644, modified from
# http://justinlilly.com/python/virtualenv_wrapper_helper.html, linked from
# http://virtualenvwrapper.readthedocs.org/en/latest/tips.html
#automatically-run-workon-when-entering-a-directory
check_virtualenv() {
    if [ -e .venv ]; then
        env=`cat .venv`
        if [ "$env" != "${VIRTUAL_ENV##*/}" ]; then
            echo "Found .venv in directory. Calling: workon ${env}"
            workon $env
        fi
    fi
}
venv_cd () {
    builtin cd "$@" && check_virtualenv; ls -FGlAhp
}
# Call check_virtualenv in case opening directly into a directory (e.g
# when opening a new tab in Terminal.app).
check_virtualenv
alias cd="venv_cd"

答案 2 :(得分:2)

我在.bashrc文件中使用此功能自动workon最近激活的虚拟环境。

if [ -f  /usr/local/bin/virtualenvwrapper.sh ]; then
  source /usr/local/bin/virtualenvwrapper.sh

  # Set up hooks to automatically enter last virtual env
  export LAST_VENV_FILE=${WORKON_HOME}/.last_virtual_env
  echo -e "#!/bin/bash\necho \$1 > $LAST_VENV_FILE" > $WORKON_HOME/preactivate
  echo -e "#!/bin/bash\necho '' > $LAST_VENV_FILE" > $WORKON_HOME/predeactivate
  chmod +x $WORKON_HOME/preactivate
  chmod +x $WORKON_HOME/predeactivate
  if [ -f  $LAST_VENV_FILE ]; then
    LAST_VENV=$(tail -n 1 $LAST_VENV_FILE)
    if [ ! -z $LAST_VENV ]; then
      # Automatically re-enter virtual environment
      workon $LAST_VENV
    fi
  fi
fi

preactivatedeactivate挂钩被修改,以便在激活虚拟环境时,将虚拟环境的名称转储到文件中,当它被停用时,文件的内容将被删除。这类似于@Todd Vanyo的回答,但在激活/停用而不是导航目录时有效。

相关问题