【问题标题】:How to import functions of a jupyter notebook into another jupyter notebook in Google Colab如何在 Google Colab 中将 jupyter notebook 的功能导入另一个 jupyter notebook
【发布时间】:2020-03-20 01:07:29
【问题描述】:

我想将 Jupyter 笔记本(以 .ipynb 结尾)的功能导入另一个 Jupyter 笔记本。

两个笔记本都位于 Google 云端硬盘中的同一个文件中。应导入其他笔记本功能的笔记本已在 Google Colab 中打开。

因此,我正在寻找类似的代码

from  xxx.ipynb  import functionX

我已经安装了 PyDrive 包装器并验证并创建了 PyDrive 客户端,如下所示:

!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)

【问题讨论】:

    标签: import google-drive-api jupyter-notebook google-colaboratory


    【解决方案1】:

    您可以使用import_ipynb 库。

    首先,安装你的谷歌驱动器以访问你的 xxx.ipynb

    from google.colab import drive
    drive.mount("mnt")
    

    然后将目录切换到笔记本目录。

    %cd "mnt/My Drive/Colab Notebooks"
    

    现在安装 import_ipynb 库并导入它

    !pip install import-ipynb
    import import_ipynb
    

    现在您可以导入您的xxx.ipynb

    import xxx
    xxx.do_something()
    

    这是example Colab

    更新(2020 年 10 月)

    我只安装了kora 并调用了一个函数,从而简化了这个过程。

    (请在新笔记本中也使用auto-mount

    !pip install kora -q
    from kora import drive
    drive.link_nbs()
    

    现在您可以从之前制作的任何笔记本中导入。例如,如果您已经拥有mylib.ipynb,则可以

    import mylib
    mylib.do_something()
    

    【讨论】:

    • 不挂载衍生还有其他解决方案吗?
    【解决方案2】:

    您可以在不更改目录的情况下按照以下方法:

    source_path_file = '/content/drive/My Drive/Colab Notebooks/Works/functions.ipynb'
    source_path_file = source_path_file.replace(' ', '\\ ')
    
    !cp $source_path_file '/content' # to copy the file from drive to colab
    
    !rsync -aP $source_path_file '/content/functions.ipynb' # run this line to sync with the parent file in case you made any changes
    
    import import_ipynb
    import functions as fn
    #as i'm importing functions.ipynb in my case
    

    如果您想导入函数文件而不安装到驱动器。您将不得不从某个地方导入函数文件,您可以从上面的“导入部分”中进行操作。

    【讨论】:

      【解决方案3】:

      最简单的方法:

      1. 装载 Google 云端硬盘
      2. 安装ipybn 模块
      3. cd 到你的工作目录
      4. 运行from ipynb.fs.defs.<the notebook name> import <the things you want to import>

      例子:

      !pip install ipynb
      %cd /your/working/directory
      from ipynb.fs.defs.notebook_to_import import class1, class2, func1, func2
      

      【讨论】: