Search code examples
pythonjupyter-notebookpipenvjupyter-kernel

Pipenv-aware jupyter kernel


I use one (project-independent, installed with pipx) jupyter notebook (or lab) installation, and then separate virtual environments for each project (using pipenv). If I open a notebook in one of the projects, it will run using the system python by default. If I want it to run using the virtual environment's python, I have to install ipykernel into the venv and the let the global jupyter installation know that it exists by running inside the venv python -m ipykernel install --user --name project-pipenv. I can then select the correct kernel from inside jupyter.

Now I have 20+ projects, so my list of kernels is rather long. Is it possible to automatically use the correct kernel?


Solution

  • Rather than using one kernel definition by project, we can make the kernel definition pipenv-aware. Create (or edit/copy an existing kernel definition at ~/.local/share/jupyter/kernels/pipenv/kernel.json (linux) ~/Library/Jupyter/kernels/pipenv/kernel.json (Mac) or %APPDATA%\jupyter\kernels\pipenv\kernel.json (Windows):

    {
     "argv": [
      "pipenv",
      "run",
      "python",
      "-m",
      "ipykernel_launcher",
      "-f",
      "{connection_file}"
     ],
     "display_name": "pipenv",
     "language": "python",
     "metadata": {
      "debugger": true
     }
    }
    

    Now any notebook that sits in a pipenv project with ipykernel as a dependency will automatically use that kernel. This should be possible to adapt to poetry or others.