【问题标题】:How do I import local modules stored in my Google Drive to Google Collab?如何将存储在 Google Drive 中的本地模块导入 Google Collab?
【发布时间】:2021-05-09 07:31:14
【问题描述】:

我确实将 Google Collab 与我的 Google Drive 连接

from google.colab import drive
drive.mount('/content/drive/')

我已经可以看到我的本地 Google Drive 文件夹和文件

pwd
>> /content

ls drive/MyDrive/
>> MyFolder

但是现在,我如何导入我在/MyFolder/SubFolder/Source 中安装的本地模块?我是否必须将其间的所有目录标记为 python 模块,将__init__.py 添加到所有目录?

目前,我的笔记本位于/MyFolder,因此我可以轻松导入我的模块

from SubFolder.source.mypersonalmodule import *

交替

有没有办法从content/drive/MyDrive/MyFolder/ 运行我的笔记本?

感谢您的帮助!

【问题讨论】:

    标签: python-3.x jupyter-notebook google-colaboratory


    【解决方案1】:

    只需指定文件从drive.MyDrive 开始的位置即可。

    例如,如果我的 Google Drive 根目录中有一个文件 test_function.py,其中包含函数 square,我可以通过以下方式导入它

    from drive.MyDrive.test_function import square
    

    执行和打印路径的示例图像:

    是的,您可以从 Google 云端硬盘中的任何位置运行 Jupyter Notebook。只需找到该文件,单击它,然后在 Google 显示“没有可用预览”时单击顶部的“使用 Google Colaboratory 打开”。

    【讨论】:

    • 谢谢!我正在驱动器中运行我的 Jupyter Notebook,例如drive/MyDrive/Folder/NotebookHere。但显然,它从/content 运行,或者至少这是我运行!pwd 时返回的内容@
    • Google 的 Colab 笔记本应该足够聪明,可以根据我的回答找出路径。带有from ... import ... 的脚本导入语句应该仍然有效,因为您正在引用来自content/ 的相对路径。因此,只需将您的导入指向您的模块文件所在的位置。看起来您不需要在所有文件中都包含 __init__.py 文件(至少如果您只有一个包含所有功能的文件)。
    • 显然,它不需要__init__.py in MyDrive\, but it does require for any subfolder after/within MyDrive`。
    猜你喜欢
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 2019-03-11
    • 2011-02-12
    相关资源
    最近更新 更多