Skip to content

Instantly share code, notes, and snippets.

@sp3c73r2038
Created May 19, 2020 06:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sp3c73r2038/4976c4479a254422e9d778e415d4281a to your computer and use it in GitHub Desktop.
Save sp3c73r2038/4976c4479a254422e9d778e415d4281a to your computer and use it in GitHub Desktop.
Python virtualenv exec helper like npx in NodeJS world.
#!/bin/bash
function log() {
ts=$(date +%Y-%m-%d_%T,%6N)
level=$1
shift 1
case $level in
(err*)
echo ${ts} [ERROR]: $* 1>&2
;;
(info*)
echo ${ts} [INFO]: $*
;;
(debug*)
echo ${ts} [DEBUG] $*
;;
(*)
echo ${ts} [${level}] $* 1>&2
;;
esac
}
function find_venv() {
if [[ -d "local" && -x "local/bin/python" ]]; then
echo "local"
fi
if [[ -d ".virtualenv" && -x ".virtualenv/bin/python" ]]; then
echo ".virtualenv"
fi
if [[ -d ".venv" && -x ".venv/bin/python" ]]; then
echo ".venv"
fi
}
if [[ -z $1 ]]; then
echo "usage: pyx <command> [args...]"
exit 1
fi
venv=$(find_venv)
if [[ -z ${venv} ]]; then
log warn "cannot find any virtualenv!"
exec $@
else
log info "using virtualenv at \"${venv}\""
bin=${venv}/bin/${1}
if [[ -x ${bin} ]]; then
log info "found executable \"${bin}\""
shift 1
exec ${bin} $@
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment