【发布时间】:2019-11-26 19:41:56
【问题描述】:
我正在用 Python 3.6 编写 AWS Lambda 我有大量大空间分隔的文本文件,我需要遍历这些文件并提取前 N 行(在本例中为 1000 行)文本。一旦我有了这些行,我需要将它们放入一个新文件并将其上传到 S3。
我也不是 python 开发者,所以语言和环境对我来说是新的。
现在我正在收集 S3 对象摘要,对于其中的每一个,我都在对其进行检查,然后获取对象的数据,将其作为类文件对象打开,并将输出变量打开为一个类似文件的对象,然后进行我的处理。
我给了我的 Lambda 3GB RAM,但是 lambda 在处理任何文件之前内存不足(每个文件大约 800MB,其中大约有 210 个)。
for item in object_summary:
# Check if the object exists, and skip it if so
try:
head_object_response = s3Client.head_object(Bucket=target_bucket_name, Key=item)
logger.info('%s: Key alredy exists.' % item)
except:
# if the key does not exist, we need to swallow the 404 that comes from boto3
pass
# and then do our logic to headify the files
logger.info('Key does not exist in target, headifying: %s' % item)
# If the file doesn't exist, get the full object
s3_object = s3Client.get_object(Bucket=inputBucketName, Key=item)
long_file = s3_object['Body']._raw_stream.data
file_name = item
logger.info('%s: Processing 1000 lines of input.' % file_name)
'''
Looks like the Lambda hits a memory limit on the line below.
It crashes with 2500MB of memory used, the file it's trying
to open at that stage is 800MB large which puts it over the
max allocation of 3GB
'''
try:
with open(long_file, 'r') as input_file, open(file_name, 'w') as output_file:
for i in range(1000):
output_file.write(input_file.readline())
except OSError as exception:
if exception.errno ==36:
logger.error('File name: %s' %exception.filename)
logger.error(exception.__traceback__)
为了完整起见,我将整个函数放在上面,但我认为我可以改进的特定区域是处理文件处理的try: while: 块。
我说对了吗?还有什么地方可以改进吗?
【问题讨论】:
-
你的并发设置是多少?内存分配适用于所有正在运行的 lambda,因此如果您尝试一次处理 >2 个文件,这可能是您的问题。
-
这可能比代码审查中的人更好codereview.stackexchange.com
-
或者,从 s3 逐字节读取文件,而不是一次全部读入内存:stackoverflow.com/a/40661459/5724723,即遍历
_raw_stream -
“我把整个函数都放了”——不,你没有......请你这样做。放置所有看起来像“样板”的代码 - 没有这些代码,这些代码很难以任何有意义的方式重构。解决这个问题的方法是将事物重构为惰性生成器,但我不能将行带到我没有看到的函数之外!
-
@AndrewH AWS Lambda 内存限制设置不适用于“所有正在运行的 lambda”。它分别适用于每个 Lambda 实例。 docs.aws.amazon.com/lambda/latest/dg/resource-model.html "内存 – 函数在执行期间可用的内存量。"
标签: python memory aws-lambda boto3