Last active
July 1, 2023 01:39
-
-
Save stephanGarland/c19c136fc22115fb0b3c80c701f00233 to your computer and use it in GitHub Desktop.
A zsh function to create an ephemeral or persistent venv and and Jupyter Notebook kernel.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Requirements: | |
# jupyter-notebook: https://jupyter.org/install | |
# Python3: https://www.python.org/downloads | |
# virtualenv: https://pypi.org/project/virtualenv | |
# virtualenvwrapper: https://virtualenvwrapper.readthedocs.io/en/latest/install.html | |
# zsh | |
# Tested with Jupyter Notebook 6.5.3, Python 3.11.4, and zsh 5.8 | |
mkjup() { | |
# This is a base64-encoded skeleton of an .ipynb file, with two variables which are filled via envsubst later | |
local ipynbBase="$(cat <<EOF | |
ewogImNlbGxzIjogWwogIHsKICAgImNlbGxfdHlwZSI6ICJjb2RlIiwKICAgImV4ZWN1dGlvbl9jb3VudCI6IG51bGwsCiAgICJtZXRhZGF0YSI6IHt9LAogICAib3V0cHV0cyI6IFtdLAogICAic291cmNlIjogW10KICB9CiBdLAogIm1ldGFkYXRhIjogewogICJrZXJuZWxzcGVjIjogewogICAiZGlzcGxheV9uYW1lIjogIiR7dmVudk5hbWV9IiwKICAgImxhbmd1YWdlIjogInB5dGhvbiIsCiAgICJuYW1lIjogIiR7dmVudktlcm5lbH0iCiAgfQogfSwKICJuYmZvcm1hdCI6IDQsCiAibmJmb3JtYXRfbWlub3IiOiAxCn0K | |
EOF | |
)" | |
local isTemp=0 | |
local jupyterPID | |
local packages=() | |
local venvName="$1" | |
if [[ -z "$venvName" ]]; then | |
isTemp=1 | |
fi | |
packages+="ipykernel" | |
printf "%s\n" "Enter packages (if any) to install as newline-separated strings. Enter Ctrl+D (EOF) to exit." | |
while read -r input; do | |
if [[ "$packages" == "EOF" ]]; then | |
break | |
fi | |
packages+="$input" | |
done | |
if [[ isTemp -eq 1 ]]; then | |
mktmpenv --no-cd &>/dev/null | |
venvName=$(date '+%s') | |
else | |
mkvirtualenv "$venvName" &>/dev/null | |
fi | |
if [[ ! "$(which python3)" == *"virtualenvs"* ]]; then | |
printf "\n%s" "WARNING: No venv detected in python3 executable path - continue (Y/N)? " | |
read -r -k 1 response | |
if [[ "$response" =~ "[Nn]" ]]; then | |
printf "\n%s\n" "Aborting" | |
return 1 | |
fi | |
fi | |
export venvName | |
printf "%s\n" "${packages[@]}" > requirements.txt | |
pip install -r requirements.txt | |
local venvKernel="$(python3 --version)-venv-${venvName}" | |
export venvKernel="${${venvKernel/ /}:l}" | |
python3 -m ipykernel install --user --name="$venvKernel" | |
base64 --decode <<< "$ipynbBase" | envsubst > "${venvName}.ipynb" | |
rm requirements.txt | |
jupyter-notebook "${venvName}.ipynb" | |
jupyterPID=$! | |
wait $jupyterPID &>/dev/null | |
if [[ $isTemp -eq 1 ]]; then | |
jupyter-kernelspec uninstall -y "$venvKernel" | |
rm "${venvName}.ipynb" | |
fi | |
deactivate | |
unset venvKernel | |
unset venvName | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment