Skip to content

Instantly share code, notes, and snippets.

@wware
Last active July 6, 2017 22:50
Show Gist options
  • Save wware/e9ea0f6ba7011a3c5287b0cd47e7a8e5 to your computer and use it in GitHub Desktop.
Save wware/e9ea0f6ba7011a3c5287b0cd47e7a8e5 to your computer and use it in GitHub Desktop.
A shell script that manages my Python virtualenv, rebuilds and re-pip-installs my code, helps me with pdb debugging and performance profiling.
#!/bin/bash
PYTHON=python
help() {
echo "This is a virtualenv swiss army knife script."
echo ""
echo "Usage: $0 [options] # -S, -s, -i -c"
echo " $0 [options] foobar.py --arg1 --arg2"
echo ""
echo "-p rebuild code and pip re-install before running python"
echo "-P profile the Python code as it runs (gprof2dot)"
echo "-v DIR specify a virtualenv directory (else use .pyerc)"
echo "-d run python code in a PDB session"
echo "-S run a bash shell in the virtualenv context"
echo "-s SCRIPT run a bash script in the virtualenv context"
echo "-i go into interactive python interpreter"
echo "-c run a python code one-liner"
echo "-h,-? show this help message"
echo ""
echo "The .pyerc file should set the VIRTUAL_ENV and PIP_INSTALL variables."
echo "Example:"
echo ""
echo " VIRTUAL_ENV=\"/blah/blah/blah/venv\""
echo " PIP_INSTALL=\"...build my_package-0.0.tar.gz...store it in python-packages... && \\"
echo " pip uninstall -y my_package && \\"
echo " pip install python-packages/my_package-0.0.tar.gz\""
}
if [ $# == 0 ]
then
help
exit 0
fi
if [ -f .pyerc ]
then
source .pyerc
elif [ -f "$HOME/.pyerc" ]
then
source "$HOME/.pyerc"
fi
setup_venv() {
if [ -z "$venv_ready" ]
then
export PATH="$VIRTUAL_ENV/bin:$PATH"
unset PYTHON_HOME
venv_ready=1
fi
}
while getopts "pPv:dSs:ic:h\?" opt; do
case $opt in
p)
setup_venv
(eval $PIP_INSTALL) || exit 1
;;
P)
# PYTHON="python -m cProfile -s tottime"
PYTHON="python -m cProfile -o log.profile"
# gprof2dot -f pstats log.profile -o callingGraph.dot
# dot -Tpng callingGraph.dot -o graph.png
# display graph.png
;;
v)
VIRTUAL_ENV="$OPTARG"
;;
d)
PYTHON="python -m pdb "
;;
S)
echo "Running a bash shell in the virtualenv context..."
$PYTHON -c 'import os; os.system("/bin/bash -")'
fini="yes"
;;
s)
setup_venv
source "$OPTARG"
fini="yes"
;;
i)
setup_venv
$PYTHON
fini="yes"
;;
c)
setup_venv
$PYTHON -c "$OPTARG"
fini="yes"
;;
h|\?)
help
exit 0
;;
*)
help
exit 1
;;
esac
done
shift $(expr $OPTIND - 1)
if [ -z "$fini" ]
then
setup_venv
$PYTHON $@
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment