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

4 投票
3 回答
14034 浏览
提问于 2025-04-30 16:19

每次我打开终端的时候,都得运行这个命令

source $(which virtualenvwrapper.sh)

才能使用

workon myenv

我想知道我需要在 .bashrc 文件里加些什么,这样我就可以直接使用 workon 命令,而不用先运行 source

我现在用的是 Ubuntu 14.04

暂无标签

3 个回答

2

我在我的 .bashrc 文件中使用这个设置,可以自动进入最近激活的虚拟环境。

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 的回答类似,但这个方法是在激活或关闭虚拟环境时生效,而不是在切换目录时。

2

我在我的 .bash_profile 文件里写了一些内容,目的是为了方便在不同的虚拟环境之间切换。这样做的好处是,你不需要每次都去运行那个脚本,而且还可以在你进入某个目录时,自动切换到对应的虚拟环境。

不过我有点不明白,如果你只有一个虚拟环境,那虚拟环境的意义在哪里呢?

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"
11

根据virtualenvwrapper的文档,你可以把以下内容添加到.bashrc文件中:

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

我个人比较喜欢懒加载选项,因为这样可以让命令行启动得更快。

撰写回答