2

Id like the working directory of all notebooks to be the location where I run the command from, not the location the notebook is at.

As an example:

root_folder/ 
    notebooks/
        subject_A/
            notebook.ipynb
    src/
        module.py

# notebook.ipynb

from src import module

I want to run jupyter notebook (or lab) from root_folder and import modules from the working directory. I dont consider os.chdir a good solution because moving the notebook to another folder will break the import. I'd also rather not add absolute paths inside the notebooks, this solution would not be exportable: my absolute path is not the same as yours.

I know I could add a setup.py to make src installable, but was looking for a more direct approach (I want to change the working directory, not install packages).

I also want an approach that is independent of the notebook location, it is the same regardless if it is at notebooks/A or in notebook/A/B.

Is there a way to do this?

Nilo Araujo
  • 725
  • 6
  • 15

2 Answers2

0

I would try with sys and then import module. It does not change your cwd but you will be able to import your modules in src

import sys
sys.path.append("absolute/path/to/src")

from module import *
thomask
  • 743
  • 7
  • 10
0

Find root_folder like this:

import os 

# Get current working directory, in your case cwd is ../root_folder/notebooks/subject_A

cwd = os.getcwd()

root_folder = os.path.dirname(os.path.dirname(cwd))

After finding root_folder:

path_to_src = os.path.join(root_folder, 'src')

And finally, append path_to_src to sys.path :

import sys
sys.path.append(path_to_src)

Now Python can import any modules from src. If the root_folder is moved to other system or directory the above-mentioned procedure will be able to import any modules from src.

Pouya Esmaeili
  • 1,265
  • 4
  • 11
  • 25