我的目标是在AWS Lambda服务上运行Python 3代码,该服务目前仅支持Python 2.7。这些是我已经完成的步骤。
由于我在Mac上工作,请将docker镜像similar设置为AWS Lambda Linux实例。
Build Python3。
在泊坞窗图片中创建虚拟环境并将其复制到我的项目中。
AWS Lambda要求您创建代码的zip并将其上传到其服务。对于这个原型,我在根目录下有一个带有三个工件的拉链
handler.py
:这是一个Python 2.7文件。发生事件时,AWS Lambda Service将执行此文件中的handler
功能(例如,在S3存储桶中创建新文件时)。
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
。我已经取出了使用它的代码以简洁,但我确实需要它,我正在使用argparse
来提取它。
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
文件夹。这是我从docker镜像中复制的虚拟环境文件夹。当我运行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\'
注意:
如果我删除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']
注意:
source venv/bin/activate
中的handler.py
命令。这在Lambda实例上不起作用,尽管它在本地工作。 答案 0 :(得分:0)
创建虚拟环境不会复制/usr/local/lib/python3.6
目录中的所有模块。我不得不复制那里的所有文件。