Skip to content

Instantly share code, notes, and snippets.

@wxiaoguang wxiaoguang/venv.sh
Last active Jul 16, 2019

Embed
What would you like to do?
python3 virtualenv/venv helper bash script (env init, env bootstrap, pip requirement installation, program exec)
#!/bin/bash
SYSTEM_PYTHON="python3.6"
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
export VIRTUAL_ENV="$DIR/.venv"
PIP="$VIRTUAL_ENV/bin/pip"
PYTHON="$VIRTUAL_ENV/bin/python"
if [[ ! -e "$VIRTUAL_ENV" ]]; then
if ! "$SYSTEM_PYTHON" -m venv "$VIRTUAL_ENV"; then
echo "can not init venv"
exit 1
fi
if [[ ! -f "$PIP" ]]; then
get_pip="$VIRTUAL_ENV/bin/get-pip.py"
curl https://bootstrap.pypa.io/get-pip.py -o "$get_pip"
if ! "$PYTHON" "$get_pip"; then
echo "can not install pip"
exit 1
fi
fi
"$PIP" install wheel
fi
export PATH="$VIRTUAL_ENV/bin:$PATH"
hash -r
cmd=$1
shift
if [[ "$cmd" = "setup" && "$1" = "" ]]; then
exec "$PIP" install -r "$DIR/requirements.txt"
elif [[ "$cmd" == "" ]]; then
dir_name=$(basename "$DIR")
exec bash --rcfile <(cat ~/.bashrc 2>/dev/null; echo "PS1=\"($dir_name) \$PS1\"")
fi
exec "$cmd" "$@"
# how to use:
# $ ./venv.sh -- init and get a bash shell with venv prompt
# $ ./venv.sh setup -- init and install pip requirements
# $ ./venv.sh pip ... -- run programs in venv
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.