【发布时间】:2014-12-26 20:12:06
【问题描述】:
每次打开终端我都必须运行这个命令
source $(which virtualenvwrapper.sh)
使用
workon myenv
我想知道我需要添加到 .bashrc 中的内容,以便我可以立即使用 workon 命令,
之前没有使用source
我使用的是 Ubuntu 14.04
【问题讨论】:
标签: python virtualenv
每次打开终端我都必须运行这个命令
source $(which virtualenvwrapper.sh)
使用
workon myenv
我想知道我需要添加到 .bashrc 中的内容,以便我可以立即使用 workon 命令,
之前没有使用source
我使用的是 Ubuntu 14.04
【问题讨论】:
标签: python virtualenv
根据virtualenvwrapper docs,您可以将以下内容添加到.bashrc:
export WORKON_HOME=$HOME/.virtualenvs
export PROJECT_HOME=$HOME/Devel
source /usr/local/bin/virtualenvwrapper.sh
我个人喜欢lazy loading option,因为它可以保持shell启动速度很快。
【讨论】:
.sh 文件sometimes gets put elsewhere(例如pip install)
我的 .bash_profile 中有这个来帮助在虚拟环境之间移动。它包括不必每次都获取 shell 脚本所需的信息,但它还包括一种在您 cd 进入目录时自动“工作”环境的方法。
如果你只有一个,我不确定我是否明白 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"
【讨论】:
我在我的.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
修改了preactivate 和deactivate 挂钩,以便在激活虚拟环境时将虚拟环境的名称转储到文件中,而在停用时删除文件的内容。这类似于@Todd Vanyo 的答案,但在激活/停用而不是导航目录时有效。
【讨论】: