Skip to content

Instantly share code, notes, and snippets.

@wxiaoguang
Last active July 16, 2019 09:54
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save wxiaoguang/88dc7d7b56456da2b37ab5d0b9dd9209 to your computer and use it in GitHub Desktop.
Save wxiaoguang/88dc7d7b56456da2b37ab5d0b9dd9209 to your computer and use it in GitHub Desktop.
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