Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

后端 未结 7 1206
灰色年华
灰色年华 2020-12-04 05:23

I have a directory structure similar to the following

meta_project
    project1
        __init__.py
        lib
            module.py
            __init__.py         


        
相关标签:
7条回答
  • 2020-12-04 06:16

    Researching this topic myself and having read the answers I recommend using the path.py library since it provides a context manager for changing the current working directory.

    You then have something like

    import path
    if path.Path('../lib').isdir():
        with path.Path('..'):
            import lib
    

    Although, you might just omit the isdir statement.

    Here I'll add print statements to make it easy to follow what's happening

    import path
    import pandas
    
    print(path.Path.getcwd())
    print(path.Path('../lib').isdir())
    if path.Path('../lib').isdir():
        with path.Path('..'):
            print(path.Path.getcwd())
            import lib
            print('Success!')
    print(path.Path.getcwd())
    

    which outputs in this example (where lib is at /home/jovyan/shared/notebooks/by-team/data-vis/demos/lib):

    /home/jovyan/shared/notebooks/by-team/data-vis/demos/custom-chart
    /home/jovyan/shared/notebooks/by-team/data-vis/demos
    /home/jovyan/shared/notebooks/by-team/data-vis/demos/custom-chart
    

    Since the solution uses a context manager, you are guaranteed to go back to your previous working directory, no matter what state your kernel was in before the cell and no matter what exceptions are thrown by importing your library code.

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