importing functions from another jupyter notebook

前端 未结 1 2022
無奈伤痛
無奈伤痛 2020-12-15 19:24

I am trying to import a function from another jupyter notebook

In n1.ipynb:

def test_func(x):
  return x + 1
-> run this

In n2.i

1条回答
  •  轮回少年
    2020-12-15 20:03

    The nbimporter module helps us here:

    pip install nbimporter
    

    For example, with two notebooks in this directory structure:

    /src/configuration_nb.ipynb

    analysis.ipynb

    /src/configuration_nb.ipynb:

    class Configuration_nb():
        def __init__(self):
            print('hello from configuration notebook')
    

    analysis.ipynb:

    import nbimporter
    from src import configuration_nb
    
    new = configuration_nb.Configuration_nb()
    

    output:

    Importing Jupyter notebook from ......\src\configuration_nb.ipynb
    hello from configuration notebook
    

    We can also import and use modules from python files.

    /src/configuration.py

    class Configuration():
        def __init__(self):
            print('hello from configuration.py')
    

    analysis.ipynb:

    import nbimporter
    from src import configuration
    
    new = configuration.Configuration()
    

    output:

    hello from configuration.py
    

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