如何在 cd 进入目录时自动激活 virtualenvs [英] How to automatically activate virtualenvs when cd'ing into a directory

查看:40
本文介绍了如何在 cd 进入目录时自动激活 virtualenvs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 ~/Documents 中有一堆项目.我几乎只在 python 中工作,所以这些基本上都是 python 项目.每一个,例如~/Documents/foo 有自己的 virtualenv,~/Documents/foo/venv(它们总是被称为 venv).每当我在项目之间切换时(每天约 10 次),我都会这样做

I have a bunch of projects in my ~/Documents. I work almost exclusively in python, so these are basically all python projects. Each one, e.g. ~/Documents/foo has its own virtualenv, ~/Documents/foo/venv (they're always called venv). Whenever I switch between projects, which is ~10 times a day, I do

deactivate
cd ..
cd foo
source venv/bin/activate

我已经厌倦了输入deactivatesource venv/bin/activate.我正在寻找一种方法,只需 cd ../foo 并为我处理 virtualenv 操作.

I've reached the point where I'm sick of typing deactivate and source venv/bin/activate. I'm looking for a way to just cd ../foo and have the virtualenv operations handled for me.

  • 我熟悉 VirtualEnvWrapper,它有点笨手笨脚我的看法.据我所知,它似乎将您所有的 virtualenvs 移动到其他地方,并且增加了比它删除的更多的复杂性.(欢迎提出不同意见!)

  • I'm familiar with VirtualEnvWrapper which is a little heavy-handed in my opinion. It seems to move all your virtualenvs somewhere else, and adds a little more complexity than it removes, as far as I can tell. (Dissenting opinions welcome!)

我对 shell 脚本不太熟悉.如果你能推荐一个低维护的脚本来添加到我的 ~/.zshrc 中来完成这个,那就足够了,但是从一些快速的谷歌搜索中,我还没有找到这样的脚本.

I am not too familiar with shell scripting. If you can recommend a low-maintenance script to add to my ~/.zshrc that accomplishes this, that would be more than enough, but from some quick googling, I haven't found such a script.

我是 zsh/oh-my-zsh 用户.oh-my-zsh 似乎没有这个插件.这个问题的最佳答案是有人贡献了一个 oh-my-zsh 插件来做到这一点.(如果这里的答案乏善可陈,我可能会这样做.

I'm a zsh/oh-my-zsh user. oh-my-zsh doesn't seem to have a plugin for this. The best answer to this question would be someone contributing an oh-my-zsh plugin which does this. (Which I might do if the answers here are lackluster.

推荐答案

把这样的东西放到你的 .zshrc 中

Put something like this in your .zshrc

function cd() {
  if [[ -d ./venv ]] ; then
    deactivate
  fi

  builtin cd $1

  if [[ -d ./venv ]] ; then
    . ./venv/bin/activate
  fi
}

编辑:如注释中所述,cd 进入当前虚拟环境的子文件夹将停用它.一种想法可能是仅当 cd-ing 进入一个新环境时才停用当前环境,例如

Edit: As noted in comments cd-ing into a subfolder of the current virtual env would deactivate it. One idea could be to deactivate the current env only if cd-ing into a new one, like

function cd() {
  builtin cd $1

  if [[ -n "$VIRTUAL_ENV" && -d ./venv ]] ; then
    deactivate
    . ./venv/bin/activate
  fi
}

仍然可以改进,也许将其变成提示命令"或 尝试在文件夹名称上进行一些前缀匹配 以检查路径上某处是否存在虚拟环境,但我的 shell-fu 不够好.

that could still be improved, maybe turning it into a "prompt command" or attempting some prefix matching on the folder names to check there's a virtual env somewhere up the path, but my shell-fu is not good enough.

这篇关于如何在 cd 进入目录时自动激活 virtualenvs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆