pythonimportpathjupyter-labpythonpath

How to add to the pythonpath in jupyter lab


I am trying to work with jupyterlab on a remote server that I don't manage, and I want to add my custom libraries to the path so that I can import and use them. Normally, I would go into .bashrc and add to PYTHONPATH there using

export PYTHONPATH="/home/username/path/to/module:$PYTHONPATH"

but this hasn't worked. I have tried this in .bashrc and .bash_profile to no fortune. I have also tried

export JUPYTER_PATH="/home/username/path/to/module:$JUPYTER_PATH"

as I read that somewhere else, and tried it in both the files named above.

What else can I try?

Ideally I'd like to put in some line in jupyterlab that returns the file it is using to add to the path, is that possible?

Or perhaps there is some command I can type directly into a terminal that I can access through jupyterlab that would allow me to add things to my path perminantley. I know that I can use os.path.insert (or similar) at the start of a notebook but as there are certain things I will want to use in every notebook this is a less than ideal solution for me.

Thanks


Solution

  • In a Specific Notebook

    Manually append the path to sys.path in the first cell of the notebook

    import sys
    extra_path = "/home/username/path/to/module" # whatever individual directory it is
    if extra_path not in sys.path:
        sys.path.append(extra_path)
    

    Note that sys.path is a list of individual directories.

    As a System Configuration

    Modify ~/.ipython/profile_default/ipython_config.py using the shell functionality so that the path gets modified for every notebook.

    If that file does not exist, create it by using ipython profile create.

    Then insert the modification to sys.path into it by modifying the c.InteractiveShellApp.exec_lines variable, e.g.

    c.InteractiveShellApp.exec_lines = [
     'import sys; sys.path.append(<path to append>)'
    ]
    

    Partially stolen from this answer, which has a different enough context to warrant being a different question.