我想将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)
答案 0 :(得分:2)
您可以使用import_ipynb
库。
首先,安装您的Google驱动器以访问您的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。
答案 1 :(得分:0)
您可以按照以下方法进行操作而无需更改目录:
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
如果要导入功能文件而不装入驱动器。您将必须从某个位置导入功能文件,并且可以从“导入部分”中按照上述步骤进行操作。
答案 2 :(得分:0)
最简单的方法:
ipybn
模块cd
到您的工作目录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