python - Lambda + Python + 退出代码

标签 python amazon-web-services aws-lambda

我遇到了一个用 Python 编写的简单 AWS Lambda 函数的问题。

当我运行我的 Lambda 函数时,我的代码按预期运行,结果是正确的,但仍然以错误代码(退出代码)结束:“Process exited before completing request”,这导致 Lambda 运行 3 次(异步)。

您是否有管理 Lambda 退出代码的最佳实践?

#!/usr/bin/python

import boto3
import sys
import tweepy
import datetime

session = boto3

# Init s3 client
s3 = session.resource('s3')

def get_data_and_push(s3_bucket, s3_key, user):
    # Retrieve CSV file
    try:
        dest = s3.Object(s3_bucket, s3_key)
        dest.download_file(tmpfile)
    except Exception, e:
        print 'An error occured while trying to download CSV file'
        print 'This exception has been thrown :'
        print e
        sys.exit(1)

    # Authenticate to Twitter
    try:
        auth = tweepy.OAuthHandler(t_consumer_key, t_consumer_secret)
        auth.set_access_token(t_access_token_key, t_access_token_secret)
        api = tweepy.API(auth)
    except Exception, e:
        print 'Cannot authenticate to Twitter.'
        print 'This exception has been thrown :'
        print e
        sys.exit(2)

    data = api.get_user(user)
    print 'User : ' + data.screen_name
    print 'Followers : ' + str(data.followers_count)
    print 'Friends : ' + str(data.friends_count)
    print '-----------'

    # Get today's date
    today = datetime.datetime.now().strftime("%Y-%m-%d")

    # Write result
    try:
        # Write result at the end of the file
        file = open(tmpfile, 'a')
        file.write(today + ',' + str(data.followers_count) + ',' + str(data.friends_count)+ '\n')
        file.close()
    except Exception, e:
        print 'Unable to write in temp file'
        print 'This exception has been thrown :'
        print e
        sys.exit(5)

    # Upload final file
    try:
        # Push file to S3
        dest.upload_file(tmpfile)
    except Exception, e:
        print 'An error occured while trying to upload CSV file'
        print 'This exception has been thrown :'
        print e
        sys.exit(6)

def main(event, context):
    for user in userlist:
        get_data_and_push(bucket, 'export_' + user + '.csv', user)
    sys.exit(0)

谢谢你的帮助,

最佳答案

是的,删除代码末尾的 sys.exit(0),应该这样做:-)


更长

通过执行 sys.exit(0),您实际上停止了在 Lambda 函数中运行您的代码的进程。这不是执行者所期望的。

我假设 Lambda 函数的处理程序实际上是在 AWS 的框架内运行的。因此,您已经处于 python 进程中,并且您的处理程序在 AWS 代码的某处被调用。因此,如果您退出该过程,您实际上是在缩短 AWS 的框架,该框架无法处理 Lambda 执行的解析。

关于python - Lambda + Python + 退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52739632/

相关文章:

Java Appium 测试无法在 AWS Device Farm 上运行

amazon-web-services - 如何强制重新加载 lambda 函数的全局变量?

aws-lambda - AppSync 与 AWS4 和混合身份验证类型(用户池和 IAM)

python - 如何计算 Pandas 前 N 行的累计和?

python - 有没有办法在 openCV 中使用条件内核,仅在条件为真时才更改图像上的像素?

amazon-web-services - 如何增加 AWS CPU 积分余额降为零?

java - 这里有人成功地将 Micronaut GraphQL API 部署到 AWS Lambda 吗?

python - Pandas导入CSV和Excel文件报错

python - 最小的正 float64 数字

amazon-web-services - aws - 浏览网站 - 找不到 404 - 没有这样的桶