Skip to content

Instantly share code, notes, and snippets.

@telamonian
Forked from thvitt/register-jupyter-env
Last active March 3, 2021 11:46
Show Gist options
  • Save telamonian/8f3a42cc98dbf08a8e1a8f7c4e8c2588 to your computer and use it in GitHub Desktop.
Save telamonian/8f3a42cc98dbf08a8e1a8f7c4e8c2588 to your computer and use it in GitHub Desktop.
Register a jupyter kernel for the current pyenv (with fix for Jupyter servers running in virtualenvs).
#!/bin/sh
if [ "$PYENV_VERSION" -ne "" ]
then
name=`pyenv version-name`
python=`pyenv which python`
else
name=`basename "$VIRTUAL_ENV"`
python="$VIRTUALENV/bin/python"
fi
jupyterdir=$(jupyter --data-dir)
kerneldir="${jupyterdir}/kernels/${name}"
echo "Installing jupyter kernel file $name for $python to $kerneldir ..."
pip install ipykernel
mkdir -p "$kerneldir"
cat > "$kerneldir"/kernel.json <<EOF
{
"argv": [ "$python", "-m", "ipykernel", "-f", "{connection_file}" ],
"display_name": "$name",
"language": "python",
"env": {"__PYVENV_LAUNCHER__": ""}
}
EOF
cat "$kerneldir"/kernel.json
@telamonian
Copy link
Author

Following @thvitt's general approach, I was eventually able to set up completely isolated Jupyter kernels for multiple different Pythons (cpy37, cpy38, cpy39, etc) installed using pyenv.

However, becuase I run my Jupyter servers from within virtual environments (created using the builtin python -m venv command), I ran into some challenging bugs along the way. The fix was to add an env entry to kernel.json that zeros out the __PYVENV_LAUNCHER__ variable.

The __PYVENV_LAUNCHER__ bug was also fixed upstream in cpython itself in 3.9.0, and backported to 3.7.9 and 3.8.? (not sure exactly which minor version). So if you run into this bug, you can also fix it by just upgrading your virtual env to the latest Python release.

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