[Python] How to use virtual environments in Jupyter Notebook in VS Code

Discussão em 'Python' iniciado por Stack, Abril 8, 2025.

  1. Stack

    Stack Membro Participativo

    I use Jupyter extension (v2024.10.0), Python (v2024.20.0), and Pylance (v2024.12.1) with default interpreter path, VS Code 1.95.3 on MacOS Sonoma 14.6. I want to debug Python code interactively in jupyter notebooks using the same virtual environment I use when running modules via Terminal.

    e.g. I have a project with these files:

    • test.ipynb
    • script.py

    I run my script like this:

    $ source ~/envs/my-project-env/bin/activate
    (my-project-env) $ python script.py


    I would like to use my-project-env environment in the Jupyter notebook. I click Select Kernel top right, but it doesn't appear in the drop-down.

    [​IMG]

    Next I try the tip here and use ipython kernel install --user --name=my-project-env. It creates the kernel, and I can select it from the Jupyter Kernel... list instead, but it uses the wrong Python path, pointing to my global default interpreter instead.

    Next I try this tip, added my python interpreter by adding my executable's path to the list of Python Interpreters. This works great for creating a dedicated terminal for running the script.py. No need for manually sourcing my environment anymore:

    [​IMG]

    But the kernel is still unavailable for selection in Jupyter Notebook "Select Kernel" list. How can I run the Jupyter Notebook and get the same code auto-completion using the same environment as my script?

    Continue reading...

Compartilhe esta Página