I am a python developer and usually work with multiple repositories at any time. Most of these projects have different dependencies so I create a virtual environment in every project. I prefer creating virtual env right next to code. Pycharm also detects it when repository is opened in Pycharm.
This setup worked most of the time but sometimes, I activate venv of one repository and then change it another repository without changing activating correct environment. I usually spotted this when code execution used to fail and never lost more than a minute on this but, this always made me think what if there is a shell that could run something when you enter a directory?
I decided to implement something simple in shell script temporarily. I ended up with creating small function, aliased with cd and added in my .bashrc.
It's a simple function and all I ever needed. It does,
I was okay with not deactivating/resetting environment when i exited the directory.
Add below function in .bashrc and you should be able to use it.
Note: If you create your virtual environment with different name then please change the name in code below.
function cd() { # Run a shell `cd` command or error command cd "$@" || return # If .venv exists in the directory if [[ -d .venv ]]; then # Deactivate any initialized virtual env, ignore error deactivate > /dev/null 2>&1 # activate .venv source .venv/bin/activate echo "deactivate prev venv and activate current venv" fi # Load a .cdenv file if [[ -f .cdenv ]]; then echo "loading .cdenv" source ./.cdenv fi }
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3