Skip to content

Instantly share code, notes, and snippets.

@Hosuke
Forked from wxiaoguang/venv.sh
Last active May 31, 2019 10:14
Show Gist options
  • Save Hosuke/06b86ffa268d9675db76a3b5284acaaa to your computer and use it in GitHub Desktop.
Save Hosuke/06b86ffa268d9675db76a3b5284acaaa to your computer and use it in GitHub Desktop.
python3 virtualenv/venv helper bash script (env init, env bootstrap, pip requirement installation, program exec) with explanation
#!/bin/bash
# Go to the location where your script located wherever your run it,
# and store the path contains the script at DIR.
# ${BASH_SOURCE[0]} is a more precised way to locate compare to $0
# https://stackoverflow.com/questions/35006457/choosing-between-0-and-bash-source
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
# Set DIR as the working directory.
# If the directory does not have the .venv folder,
# then we create a new one and install wheel inside.
export VIRTUAL_ENV="$DIR/.venv"
if [[ ! -e "$VIRTUAL_ENV" ]]; then
if ! python3 -m venv "$VIRTUAL_ENV"; then
echo "can not init venv"
exit 1
fi
"$VIRTUAL_ENV/bin/pip" install wheel
fi
# Set the virtual env to PATH
export PATH="$VIRTUAL_ENV/bin:$PATH"
# Clean the bash cache and from now on for the new command bash need to lookup the PATH
hash -r
# Get the first arg after venv.sh
cmd=$1
# Renamed #n to #n-1 at this case
shift
# If cmd is setup
# then we install requirements in the venv
if [[ "$cmd" = "setup" && "$1" = "" ]]; then
exec pip install -r "$DIR/requirements.txt"
# If no cmd
# then we place a (dirname) before the command line identifier
# eg. (py3)~
elif [[ "$cmd" == "" ]]; then
dir_name=$(basename "$DIR")
exec bash --rcfile <(cat ~/.bashrc 2>/dev/null; echo "PS1=\"($dir_name) \$PS1\"")
fi
# Finally we run the cmd with the rest of args
# $@ means args except $0
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