pythonvisual-studio-codejupyter-notebookjupyter-server

Set import path for python with jupyter notebooks / vscode


I connect to my own jupyter server via vpn/ssh with vscode. Jupyter server runs as a daemon.

Having asked gpt, read articles here and tried many config versions, I still end up doing this at the beginning of each notebook:

BASE_PATH = '/home/bartsimpson/dev/'

import sys

sys.path.append(BASE_PATH)

Is there a way to set it somewhere in my jupyter server or in vscode so that I could easily do this without setting path manually?

from library.myclass import MyClass

if it resides in /home/bartsimpson/dev/library/myclass.py ?

P.S. Setting neither PYTHONPATH, nor JUPYTER_PATH prior to launch helps.


Solution

  • You could go to the directory of the kernel you're using which involves the kernel.json file.

    In the same directory, create a new file called ipython_kernel_config.py.

    c = get_config()
    c.InteractiveShellApp.exec_lines = [
        "import sys",
        "sys.path.append('/home/bartsimpson/dev/')",
    ]
    

    Now, each time you start a Jupyter notebook using this kernel, the lines in exec_lines will be executed