Search code examples
pythonjupyter-notebookpython-poetry

Jupyter kernel doesn't use Poetry environment


I'm trying to install a Jupyter kernel for my poetry environment, but it seems like the kernel gets my base conda environment. Here's what I'm trying:

poetry env list
>ENV_NAME-HASH-py3.9 (Activated)

poetry run which python
>/Users/myusername/Library/Caches/pypoetry/virtualenvs/ENV_NAME-HASH-py3.9/bin/python

poetry run ipython kernel install --name=ENV_NAME
>Installed kernelspec ENV_NAME in /Users/myusername/Library/Jupyter/kernels/ENV_NAME

Then if I open a Jupyter with this kernel I don't get the libraries that should be installed. Checking the Python version I get:

!which python
/Users/myusername/opt/anaconda3/bin/python

Any help appreaciated!


Solution

  • Bonjour, I come tardily but I think I have your solution.

    If you just want to use your currently configured Poetry environment in VSCode with your .ipynb notebooks, you can do this for example:

    1. Create a new project with Poetry:

      poetry new test_ipynb
      cd test_ipynb
      
    2. Use a specific Python version with your environment:

      poetry env use 3.12
      
    3. Add ipykernel to your environment:

      poetry add ipykernel
      
    4. Check your environment's executable path:

      poetry env info
      

      Example output:

      /home/guillaume/.cache/pypoetry/virtualenvs/test-ipynb-pH8Jwd_U-py3.12/bin/python
      
    5. Open your project in VSCode:

      code .
      

    Then, in VSCode:

    Need to reload window after Ctrl + Shift + p Reload Window

    • In the top right, click on the Select Kernel.

      choose Python environment

    • Choose "Python Environments".

      Python Environments

    • And select the environment you got from the env info command.

      select the environment

    This should allow you to use your Poetry-managed virtual environment directly within VSCode for Jupyter notebooks.

    Additionally, if you want to use Jupyter or JupyterLab, just follow the steps above and add:

    poetry add jupyter
    poetry run jupyter notebook
    # For JupyterLab
    poetry add jupyterlab
    poetry run jupyter lab
    

    This ensures that your development environment is consistent across different tools and platforms, leveraging Poetry's dependency management and virtual environment capabilities directly within VSCode for Jupyter notebooks.