【发布时间】:2020-02-28 06:16:05
【问题描述】:
当我在 Google Colab 上的 Jupyter 笔记本中导入自定义 Python 包和模块时,Python 解释器会报告一条错误消息,指出“ModuleNotFoundError: No module named '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 云端硬盘托管代码目录(我的云端硬盘 -> Colab 笔记本)中,我有一个名为“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 脚本。)
【问题讨论】:
-
@TrentonMcKinney 的建议适用于 Python 模块/类,这是我所遵循的。我还使用了以下几行: from google.colab import drive drive.mount('/content/drive') 但是,我仍然无法导入 Python 包(Python 类/模块集)。
-
我也尝试了 @Himanshu Poddar 先生的建议,但在包含有关实用程序 Python 包的信息后,我无法让它工作。我使用的代码是: from google.colab import files src = list(files.upload().values())[0] #open('utilities/simple_module.py','wb').write(src) open ('./utilities/simple_module.py','wb').write(src) import mylib
标签: python python-3.x jupyter-notebook jupyter google-colaboratory