当我在Google上的朱庇特笔记本中导入一个定制的Python包和模块时,Python解释器会报告一条错误消息,指示"ModuleNotFoundError: No模块名为‘实用程序’“。
我希望能够开发一个木星笔记本,它使用来自不同Python类/模块的函数,这些函数来自我开发和测试过的不同Python包。
我简化了我的木星笔记本,在一个Python包中对唯一的Python模块/类进行函数调用,该包存储在Google上的同一个目录中。
木星笔记本的源代码是:
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托管代码目录中,我有一个名为“实用程序”的文件夹,其中有一个名为"simple_module.py“的simple_module.py脚本。
"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中的"Colab笔记本“目录中,我还有一个名为"init.py”的文件。
其内容如下:
from .utilities import *我需要做什么才能使用我创建和彻底测试的Python中的模块/类?
P/S:How to import custom modules in google colab?中的问题和解决方案没有涉及导入嵌入在packages中的Python模块。
我可以在目录中导入Python模块,用于GoogleColab木星笔记本的Google托管代码(我的驱动器-> Colab笔记本)。
但是,我遇到了一些问题,包括存储在Python包中的Python模块/类(文件夹/目录的子目录,包括Python脚本和Python程序的主函数)。
发布于 2020-02-11 18:05:07
到2020年2月,你可以简单地将谷歌驱动器链接到你的colab笔记本上。
现在,导航到您的.py模块所在的文件夹。
右键单击目录,然后单击复制路径。
转到您的colab笔记本并键入:
import sys
sys.path.append('your/folder/path/in/google/drive')在此之后,您应该能够使用以下方法加载colab中的模块:
from module_name import *
希望这能有所帮助!
https://stackoverflow.com/questions/58667874
复制相似问题