Last active
December 17, 2024 08:45
-
-
Save fniessink/f4142927d20fe845dc27a8ad21f340d5 to your computer and use it in GitHub Desktop.
Automatically activate and deactivate Python virtual envs on change directory
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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