首页 > 解决方案 > 如何在 Google Colab 上的 Jupyter 笔记本中导入自定义 Python 包和模块?

问题描述

当我在 Google Colab 上的 Jupyter 笔记本中导入自定义 Python 包和模块时,Python 解释器会报告一条错误消息,指示“ModuleNotFoundError:没有名为 'utilities' 的模块”。

我希望能够开发一个 Jupyter 笔记本,它使用来自我开发和测试的不同 Python 包的不同 Python 类/模块的函数。

我已经简化了我的 Jupyter 笔记本,它对存储在 Google Drive 上同一目录中的单个 Python 包中的单个 Python 模块/类进行函数调用。

Jupyter notebook 的源代码是:

import importlib.util
from google.colab import drive
drive.mount('/content/drive')
import sys
sys.path.append('/content/drive/My\ Drive/Colab\ Notebooks/utilities')
# Module to test if I can import a Python package and module.
from utilities.simple_module import simple
class Try_to_Import_Package:
    number_times_executed = 0
    #   Accessor and Mutator method.
    @staticmethod
    def get_number_times_executed():
        Try_to_Import_Package.number_times_executed = Try_to_Import_Package.number_times_executed + 1
        print(" Try_to_Import_Package 'Hello World' function called:",Try_to_Import_Package.number_times_executed,"times.")
if __name__ == "__main__":
    for x in range(10):
        simple.get_number_times_executed()
        Try_to_Import_Package.get_number_times_executed()

在我的 Google Colab Jupyter 笔记本的 Google Drive 托管代码目录中(我的 Drive -> Colab Notebooks),我有一个名为“utilities”的文件夹,其中包含一个名为“simple_module.py”的 Python 脚本。

“simple_module.py”的源代码如下:

class simple:
    number_times_executed = 0
    #   Accessor and Mutator method.
    @staticmethod
    def get_number_times_executed():
        simple.number_times_executed = simple.number_times_executed + 1
        print(" simple 'Hello World' function has been called:",simple.number_times_executed,"times.")

在我的 Google Drive 的“Colab Notebooks”目录中,我还有一个名为:“ init .py”的文件。

它的内容是:

from .utilities import *

我需要做什么才能使用我创建并经过全面测试的 Python 包中的模块/类。

P/S:How to import custom modules in google colab中的问题和解决方案?不包括导入嵌入在 Python 包中的 Python 模块。

我可以在我的 Google 云端硬盘托管代码的目录中导入 Python 模块,用于 Google Colab Jupyter 笔记本(我的云端硬盘 -> Colab 笔记本)。

但是,我遇到了问题,包括存储在 Python 包中的 Python 模块/类(文件夹/目录的子目录,包括具有 Python 程序主要功能的 Python 脚本。)

标签: pythonpython-3.xjupyter-notebookjupytergoogle-colaboratory

解决方案


从 2020 年 2 月起,您只需将 google 驱动器链接到您的 colab 笔记本即可。

  1. 转到左窗格。
  2. 选择文件。
  3. 单击安装驱动器。

现在,导航到您的.py模块所在的文件夹。

右键单击目录,然后单击复制路径。

转到您的 colab 笔记本并键入:

import sys
sys.path.append('your/folder/path/in/google/drive')

在此之后,您应该能够使用以下命令在您的 colab 中加载模块:

from module_name import *

希望这可以帮助!


推荐阅读