我正在采购 virtualenvwrapper以便我可以在 bash 脚本中使用 virtualenvwrapper 函数,如下面的简化示例所示:
运行do_some ve_name branch_name
调用:
#! /bin/bash
# some script that takes parameters
source /etc/bash_completion.d/virtualenvwrapper # the magic of sourcing
workon $1 # pick a venv
cd /some/project/path
git checkout $2 # pick a branch
python do_something.py
这行得通(我不介意一旦结束就退出虚拟环境,事实上我更喜欢它)。但是,如果我已经在虚拟环境中,我会得到以下信息:
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named virtualenvwrapper.hook_loader
virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenv has been installed for VIRTUALENVWRAPPER_PYTHON=/home/username/.virtualenvs/ve_name/bin/python and that PATH is set properly.
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named virtualenvwrapper.hook_loader
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named virtualenvwrapper.hook_loader
所以让我们假设我偶尔会忘记停用我当前的 virtualenv。我尝试按如下方式解决此问题:
#! /bin/bash
# some advanced script that takes parameters
deactivate
source /etc/bash_completion.d/virtualenvwrapper # the magic of sourcing
workon $1 # pick a venv
...
但是无论我当前是否在 virtualenv 中,我都会收到以下错误(如果我不小心在 virtualenv 中,它不会停用,这是我要解决的问题):
/path/to/scripts/do_some: line 4: deactivate: command not found
那么,在采购 virtualenvwrapper 命令之前,如何防止已经在 virtualenv 中呢?