Skip to content

Instantly share code, notes, and snippets.

@ryot4
Last active May 30, 2020 18:16
Show Gist options
  • Save ryot4/65e8f96aeb79160f20fcff1fd2cde2b2 to your computer and use it in GitHub Desktop.
Save ryot4/65e8f96aeb79160f20fcff1fd2cde2b2 to your computer and use it in GitHub Desktop.
A Bash wrapper function for Python venv
venv()
{
local venv_dir
if [[ -n $VENV_ROOT ]]; then
venv_dir="${VENV_ROOT}/${2:-$(basename ${PWD})}"
else
venv_dir=.venv
fi
case "$1" in
-h)
if [[ -n $VENV_ROOT ]]; then
echo 'venv {init|activate|deactivate} [name]'
else
echo 'venv {init|activate|deactivate}'
fi
;;
init)
if [[ -d ${venv_dir} ]]; then
echo "${venv_dir} already exists" 1>&2
return 1
fi
${VENV_PYTHON_INTERPRETER:-python3} -m venv "${venv_dir}" && echo "initialized venv ${venv_dir}"
;;
activate)
if [[ -n $VIRTUAL_ENV ]]; then
echo "venv ${VIRTUAL_ENV} is already activated" 1>&2
return 1
elif ! [[ -f ${venv_dir}/bin/activate ]]; then
echo "${venv_dir}/bin/activate does not exist" 1>&2
return 1
fi
. "${venv_dir}/bin/activate" && echo "activated venv ${VIRTUAL_ENV}"
;;
deactivate)
venv_dir="${VIRTUAL_ENV}"
if [[ -z $venv_dir ]]; then
echo 'not in venv' 1>&2
return 1
fi
deactivate && echo "deactivated venv ${venv_dir}"
;;
'')
echo 'no command specified' 1>&2
return 1
;;
*)
echo "unknown command: $1" 1>&2
return 1
esac
}
_venv()
{
local cur prev
_get_comp_words_by_ref cur prev
COMPREPLY=()
case "${prev}" in
venv)
COMPREPLY=($(compgen -W '-h init activate deactivate' -- "${cur}"))
;;
activate)
if [[ -n $VENV_ROOT ]]; then
COMPREPLY=($(compgen -W "$(ls -1 "${VENV_ROOT}")" -- "${cur}"))
fi
;;
esac
}
complete -F _venv venv
@ryot4
Copy link
Author

ryot4 commented May 30, 2020

By default, .venv is used for virtual environments.
If you want to create a environment outside the current directory, set VENV_ROOT environment variable and specify the name of the environment with init and activate.

$ export VENV_ROOT=/var/tmp/venv
$ venv init project
$ venv activate project
$ venv deactivate

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment