Importing custom module into jupyter notebook

后端 未结 7 1981
眼角桃花
眼角桃花 2021-02-05 05:55

Yes, I know this is a recurrent question but I still couldn\'t find a convincing answer. I even read at https://chrisyeh96.github.io/2017/08/08/definitive-guide-python-imports.h

相关标签:
7条回答
  • 2021-02-05 06:08

    One can tell python where to look for modules via sys.path. I have a project structure like this:

    project/
        │
        ├── src/
        │    └── my_module/
        │        ├── __init__.py       
        │        └── helpers.py
        ├── notebooks/
        │   └── a_notebook.ipynb
        ...
    

    I was able to load the module like so:

    import sys
    sys.path.append('../src/')
    
    from my_module import helpers
    

    One should be able load the module from wherever they have it.

    0 讨论(0)
  • 2021-02-05 06:11

    If you move the notebooks directory out one level, and then explicitly import your module from the package, that should do it. So your directory would look like this:

    my_project/
    │
    ├── my_project/
    │   ├── __init__.py       
    │   └── helpers.py
    ├── notebooks/
    │   └── a_notebook.ipynb
    ...
    

    and then your import statement within the notebook would be:

    from my_project import helpers.

    0 讨论(0)
  • 2021-02-05 06:15

    I think you need a __init__.py module in the notebooks/ directory. I haven't really used Jupyter notebooks before so I could be wrong. You may also need to try changing your import statement to:

    import .. helpers
    

    to indicate that the import statement is for a local package that is located in the parent directory of the Jupyter notebook.

    0 讨论(0)
  • 2021-02-05 06:16

    Try the following line:

    from my_project.helpers import what_you_need

    This line should also work:

    import my_project.helpers

    0 讨论(0)
  • 2021-02-05 06:16

    This worked for me.

    import sys
    
    MODULE_FULL_PATH = '/<home>/<username>/my_project/my_project'
    
    sys.path.insert(1, MODULE_FULL_PATH)
    
    from my_module import helpers
    
    0 讨论(0)
  • 2021-02-05 06:21

    If you are on a Unix/Linux system another elegant solution may be creating a "soft link" to the module file helpers.py that you would like to use. Change to the notebooks directory and create the link to the module file this way:

    cd notebooks; ln -fs ../my_project/helpers.py .

    This "soft link" is essentially a pointer (a shortcut) to the original target file. With the link in place you will be import your module file as usual:

    import helpers

    0 讨论(0)
提交回复
热议问题