我的目標是在AWS Lambda服務上運行Python 3代碼,該服務當前僅支持Python 2.7。這些是我所做的步驟。在不激活虛擬環境的情況下運行Python3
因爲我在Mac上運行,設置泊塢窗圖像similar到AWS LAMBDA Linux實例。
Build來自Docker鏡像源碼的Python3。
在泊塢窗映像創建一個虛擬的環境,並將其複製到我的項目。
AWS Lambda需要您創建代碼的zip並將其上載到其服務。對於這個原型,我有三個神器拉鍊在根
handler.py
:這是一個Python 2.7文件。當發生事件時(例如,在S3存儲桶中創建新文件時),此文件中的handler
函數將由AWS Lambda服務執行。def handler(event, context): execution_uuid = uuid.uuid4() commands = ''' source venv/bin/activate && venv/bin/python3.6 ./handler_python3.py --execution_uuid {ex_uuid} '''.format(ex_uuid=str(execution_uuid)) p = Popen('/bin/bash', shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE, close_fds=True) stdout, stderr = p.communicate(commands) pprint(stdout) pprint(stderr)
handler_python3.py
。這是由早期的handler.py
文件調用的Python3文件。請注意正在閱讀execution_uuid
。爲了簡潔起見,我已經拿出了使用它的代碼,但我確實需要它,並且正在使用來提取它。def read_execution_uuid(): import argparse parser = argparse.ArgumentParser() parser.add_argument("--execution_uuid", required=True) args = parser.parse_args() return args.execution_uuid def handler(event, context): import sys print(sys.path) if __name__ == '__main__': execution_uuid = read_execution_uuid() handler(event, context)
venv
文件夾。這是從泊塢窗鏡像複製的虛擬環境文件夾。
當我運行AWS LAMBDA服務,我收到以下錯誤
Traceback (most recent call last):
File "./handler_python3.py", line 38, in <module>
execution_uuid = read_execution_uuid()
File "./handler_python3.py", line 7, in read_execution_uuid
import argparse
ModuleNotFoundError: No module named \'argparse\'
注:
如果我刪除代碼和
handler
功能在handler_python3.py
執行,它顯示以下納克sys.path
['/var/task', '/var/runtime', '/var/task/venv/lib/python36.zip', '/var/task/venv/lib/python3.6', '/var/task/venv/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6', '/var/task/venv/lib/python3.6/site-packages']
值的注意事項:
- 我可以argparse安裝明確。但我不想。
- 請注意python 2.7文件
handler.py
中的source venv/bin/activate
命令。儘管它在本地工作,但它不適用於Lambda實例。