如何在Google Colab的Jupyter笔记本中导入自定义Python包和模块?

How can I import a custom Python package and module in a Jupyter notebook on Google Colab?

当我在Google Colab的Jupyter笔记本中导入自定义Python包和模块时,Python解释器报告一条错误消息,指示" ModuleNotFoundError:没有名为"实用程序"的模块"。

我希望能够开发一个Jupyter笔记本,该笔记本使用我开发和测试的不同Python包中不同Python类/模块的功能。

我简化了Jupyter笔记本,该笔记本对存储在Google云端硬盘同一目录中的单个Python包中的单个Python模块/类进行了函数调用。

Jupyter笔记本的源代码为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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托管代码的目录("我的驱动器-> Colab Notebook")中,我有一个名为"实用程序"的文件夹,其Python脚本名为" simple_module.py"。

" simple_module.py"的源代码如下:

1
2
3
4
5
6
7
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云端硬盘的" Colab笔记本"目录中,我还有一个名为" init.py"的文件。

其内容为:

1
from .utilities import *

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

P / S:如何在google colab中导入自定义模块中的问题和解决方案?不涵盖如何以嵌入式Python包的形式导入Python模块。

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

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


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

  • 转到左侧窗格。
  • 选择文件。
  • 单击挂载驱动器。
  • 现在,导航到.py模块所在的文件夹。

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

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

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

    此后,您应该可以使用以下命令将模块加载到您的colab中:

    from module_name import *

    希望这会有所帮助!