How can I check I'm not in a virtualenv before sourcing virtualenvwrapper commands in bash?
我正在寻找virtualenvwrapper,以便在bash脚本中使用virtualenvwrapper函数,如下面的简化示例所示:
运行
1 2 3 4 5 6 7 8 | #! /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 |
这是可行的(我不介意在虚拟环境结束后退出,事实上我更喜欢它)。但是,如果我已经在虚拟环境中,我会得到以下信息:
1 2 3 4 5 6 7 8 9 10 | 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。我试图解决如下问题:
1 2 3 4 5 6 7 | #! /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中,它不会被停用,这是我想要解决的问题):
1 | /path/to/scripts/do_some: line 4: deactivate: command not found |
那么,在源代码为virtualenvwrapper命令之前,我如何保护自己免受已经在virtualenv中的伤害呢?
您也可以尝试使用虚拟环境变量。我发现这是一个更清晰的解决方案后,查看这个,所以我想我会留下一个注释,以防这是达到其他人寻找类似的解决方案。
例如。,
1 2 3 4 | if [ ${VIRTUAL_ENV} ] then # do some stuff fi |
下面是
1 2 3 4 5 6 | # (inside deactivate function) unset VIRTUAL_ENV if [ !"$1" ="nondestructive" ] ; then # Self destruct! unset -f deactivate fi |
以下是最初源文件时的设置方式:
1 2 3 | # (runs when you source the activate file) VIRTUAL_ENV="/path/to/venv/dir" export VIRTUAL_ENV |
这可能无法解决最初的问题(没有测试),但对于您只需要知道是否在virtualenv中的大量情况来说,这是很有帮助的。
如果我理解正确,函数
用以下命令替换您的
1 | [[ $(type -t workon) =="function" ]] || source /etc/bash_completion.d/virtualenvwrapper |