簡體   English   中英

如何在 AWS Glue 腳本中導入 python 模塊?

[英]How to import python modules in AWS Glue script?

我知道在本地機器上工作時在 python 中導入常規的 python 庫模塊。 參考圖片。 在第 5,6 行,兩種導入方式都可以正常工作。 好的。 (請注意基於顏色的下划線以便更清楚地理解)。 connection.py 文件只有一個簡單的連接 class 在此處輸入圖像描述

connection.py 文件只有一個簡單的連接 class

在此處輸入圖像描述

但是當我在 AWS 膠水(基於 pyspark)中嘗試同樣的事情時,這樣的導入不起作用。

 from mymath import HelloMsg   
# This works. Glue job completes successfully. 
# In Job Details, I have mentioned the .zip file path in AWS S3 bucket as "python library path".
# That folder is mymath.zip. It has mymath.py file. That file contains a simple HelloMsg class with a method returning Hello msg.

AWS GLue 作業具有按照標准方式提供的 zip 文件參考在此處輸入圖像描述 mymath.zip 文件夾內容: 在此處輸入圖像描述

#mymath2 is another zip file mentioned.  
#It has mymath2.py directly under it and a folder named "Connection"
#which in turn has a simple "connection.py" file

import mymath2   # This also works.  
#But Not clear why above works!. Why? (Question_1)


from mymath2 import HelloMsg  # works # so seems like it doesn't consider .zip folder name. 
#I think above works because mymath2.py file it considers and then internally it does have a hellomsg class so All in all it works 

#But below ways DOnt work.   
import mymath2.Connection  # doesn't work. Why?  (Question_2)
from mymath2.Connection import connection  # doesn't work. Why? (Question_3)
from mymath2 import mymath2  # doesn't work. Why?( Question_4). This should work assuming mymath2 zip file directly has mymath2.py. ( kindly correct if my assumptions are incorrect)

如果有人提供幫助,我將不勝感激。 我已經標記了我有問題的地方(問題 1 到 4)

我得到的錯誤信息是: 在此處輸入圖像描述

另請參閱 mymath2 文件夾結構以獲得更多清晰度。 在此處輸入圖像描述

根據錯誤,Glue 似乎期望 mymath2 是 package,而不是模塊。

A #1 - 用作您導入 mymath2 模塊
A #2-4 - 不起作用,因為您嘗試從 mymath2 package(mymath2 目錄)而不是 mymath2 模塊(mymath2 文件)導入項目。

我的理解是模塊只是一個 py 文件,而 package 可以是模塊的集合。

為了驗證這一點,您可以構建一個輪子 package 並從 s3 引用它而不是 zip。

要創建輪子,請在 Misc2 的根目錄下編寫一個 setp.py 文件,如下所示:

from setuptools import setup
setup(
    name='Misc2',
    version='0.1',
    packages={
        'mymath2'
    }
)

使用以下命令運行設置腳本並將生成的 whl 文件 (dist/Misc2-0.1-py3-none-any.whl) 上傳到 s3

python setup.py bdist_wheel

然后在您的代碼中,您應該能夠使用以下命令導入:

import mymath2.Connection
from mymath2.Connection import connection
from mymath2 import mymath2

編輯:我剛剛意識到您的 zip 僅包含 mymath2 模塊,並且不包含 Connections 目錄。 如果您不想采用上面列出的輪式方法,您可以嘗試簡單地將 Connections 目錄包含在 zip 中。 我總是采用輪式方法,因為我通常有額外的依賴項,因此可以確認它會起作用,但您可能可以繼續在此示例中使用 zip。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM