Created
November 26, 2018 09:26
-
-
Save kkew3/2a0f2ab14dd09b0438684cba94269285 to your computer and use it in GitHub Desktop.
Search for python virtualenv upwards from current directory till home directory, and source it if found. The virtualenv name is assumed to be "rt".
This file contains 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
#!/bin/bash | |
if [ "${BASH_SOURCE[0]}" = "\${0}" ]; then | |
echo This script intends to be sourced rather than be called >> /dev/stderr | |
exit 1 | |
fi | |
__findrt_upward() { | |
local acc="" | |
local targetrt="" | |
local venv="rt" # virtualenv name to search for | |
if [ -n "$1" ]; then expected_suffix="$1"; fi | |
local targetrt="" | |
# line 22-25 reverse the order of lines of stdin | |
pwd \ | |
| tr '/' '\n' \ | |
| sed '/^ *$/d' \ | |
| while read pt; do | |
acc="$acc/$pt" | |
echo "$acc" | |
done \ | |
| grep -n "" \ | |
| sed 's/^\([0-9]\+\):/\1 /' \ | |
| sort -k1 -nr \ | |
| sed 's/^\([0-9]\+\) //' \ | |
| while read pfx; do | |
if [ "$pfx" = "$HOME" ]; then | |
break | |
fi | |
if [ -f "$pfx/$venv/bin/activate" ]; then | |
echo "$pfx/$venv/bin/activate" | |
break | |
fi | |
done | |
} | |
# don't do anything unless not in virtualenv | |
if [ -z "$VIRTUAL_ENV" ]; then | |
__targetrt=$(__findrt_upward | head -1) | |
if [ -f "$__targetrt" ]; then | |
. "$__targetrt" | |
else | |
echo "virtualenv not found" >> /dev/stderr | |
fi | |
unset __targetrt | |
fi | |
unset __findrt_upward |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment