Skip to content

Instantly share code, notes, and snippets.

@fniessink
Last active December 17, 2024 08:45
Show Gist options
  • Save fniessink/f4142927d20fe845dc27a8ad21f340d5 to your computer and use it in GitHub Desktop.
Save fniessink/f4142927d20fe845dc27a8ad21f340d5 to your computer and use it in GitHub Desktop.
Automatically activate and deactivate Python virtual envs on change directory
# Include this in your .bashrc:
function activate_virtualenv () {
[[ -n $VIRTUAL_ENV ]] && deactivate;
venv=`python3 ~/.find_venv.py .`;
[[ ! -z "$venv" ]] && . $venv/bin/activate;
return 0
}
function cd () {
builtin cd "$@" && activate_virtualenv
}
# Save this script as .find_venv.py in your home directory:
import pathlib
import sys
def virtual_env(path):
"""Recursively find the virtual env, if any."""
path = path.resolve()
for each_path in [path] + list(path.parents):
try:
if virtual_envs := [d for d in each_path.iterdir() if d.is_dir() and (d / 'pyvenv.cfg').exists()]:
return str(virtual_envs[0])
except OSError:
pass
return ""
if __name__ == "__main__":
print(virtual_env(pathlib.Path(sys.argv[1])))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment