在不激活虚拟环境的情况下运行Python3

时间:2017-02-28 23:03:21

标签: python virtualenv aws-lambda

我的目标是在AWS Lambda服务上运行Python 3代码,该服务目前仅支持Python 2.7。这些是我已经完成的步骤。

  • 由于我在Mac上工作,请将docker镜像similar设置为AWS Lambda Linux实例。

  • 来自docker镜像的源代码中的
  • Build Python3。

  • 在泊坞窗图片中创建虚拟环境并将其复制到我的项目中。

  • AWS Lambda要求您创建代码的zip并将其上传到其服务。对于这个原型,我在根目录下有一个带有三个工件的拉链

    1. 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)
      
    2. 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)
      
      1. 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']
    

注意:

  • 我可以显式安装argparse。但我不愿意。
  • 请注意python 2.7文件source venv/bin/activate中的handler.py命令。这在Lambda实例上不起作用,尽管它在本地工作。

1 个答案:

答案 0 :(得分:0)

创建虚拟环境不会复制/usr/local/lib/python3.6目录中的所有模块。我不得不复制那里的所有文件。