我在GCS存储桶上具有以下结构:
如何将我的模块导入Notebook_1.ipynb? (notebook_1.ipynb是python笔记本,不是spark笔记本)
答案 0 :(得分:3)
恐怕不可能,因为您需要在运行脚本的目录中或sys.path中安装该模块。
作为一种选择,您可以实现一个功能,该功能将从您的Cloud Storage中下载该模块,使用其功能,然后将其删除。
这是我为测试目的编写的一个简单的示例:
greetings.py (我存储在存储桶中的文件):
def say_hello(name):
return "Hello {}!".format(name)
def say_hi(name):
return "Hi {}!".format(name)
main.py :
from google.cloud import storage
import os
def get_module():
"""
Instantiate Storage Client and return the blob located in the bucket.
"""
client = storage.Client()
bucket = client.get_bucket('<my-bucket-name>')
return bucket.blob('greetings.py')
def use_my_module(my_method, val):
"""
Download the module, use it and then remove.
"""
blob = get_module()
blob.download_to_filename('my_module.py')
import my_module
result = getattr(my_module, my_method)(val)
os.remove('my_module.py')
return result
print(use_my_module('say_hello', 'User 1'))
print(use_my_module('say_hi', 'User 2'))
输出:
Hello User 1!
Hi User 2!
我无法确定上面的示例对于您的情况是否有效,但我希望它能给您一些想法。
关于使用脚本(notebook_1.ipynb)将模块放置在目录的子目录中的情况-您可以像这样导入模块:
import modules.mymodule
然后您可以将其用于以下结构:
modules.mymodule.<your-method>