【问题标题】:How to read Txt file from S3 Bucket using Python And Boto3如何使用 Python 和 Boto3 从 S3 Bucket 读取 Txt 文件
【发布时间】:2021-03-12 15:52:38
【问题描述】:

如何使用 Python 和 Boto3 从 S3 Bucket 读取 Txt 文件 我正在使用以下运行良好的脚本我能够看到 S3 存储桶中的实例名称

import boto3
import codecs

access_key = "XXXXXXXXXXXX"
secret_key = "XXXXXXXXXXXXXXXxxxxx"
ec2 = boto3.client('ec2', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name='us-east-1')

s3 = boto3.resource('s3', aws_access_key_id=access_key, aws_secret_access_key=secret_key, region_name='us-east-1')

bucket = 'stoppedinstanceidslist'
key = 'StoppedInstanceidsList.txt'
obj = s3.Object(bucket, key)
InstancetobeStart = (obj.get()['Body'].read().decode('utf-8'))
ids=InstancetobeStart
print(type(ids))   # <class 'str'>
print(ids)  #  ['i-041fb789f1554b7d5', 'i-0d0c876682eef71ae']

response =ec2.start_instances(InstanceIds=ids)

print("Your Instances are Started now which are stopped last day")

使用响应后出现以下错误

    raise ParamValidationError(report=report.generate_report())
botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter InstanceIds, value: ['i-041fb789f1554b7d5', 'i-0d0c876682eef71ae'], type: <class 'str'>, valid types: <class 'list'>, <class 'tuple'>
<class 'str'>
['i-041fb789f1554b7d5', 'i-0d0c876682eef71ae']

如果我的程序在从 s3 存储桶读取后停止实例该怎么办

【问题讨论】:

  • 这能回答你的问题吗? python boto3 parameter validation error
  • 实际上没有在这里我从 S3 存储桶文件中读取而不是从描述实例中读取我的 s3 中已经有一个实例列表

标签: python python-3.x amazon-web-services boto3 boto


【解决方案1】:

您的ids 是文字字符串['i-041fb789f1554b7d5', 'i-0d0c876682eef71ae'],而不是列表。要解析它并转换为列表,请使用ast 模块:

import ast
# ...
InstancetobeStart = (obj.get()['Body'].read().decode('utf-8'))
ids = ast.literal_eval(InstancetobeStart)

【讨论】:

    猜你喜欢
    • 2017-04-21
    • 2021-05-22
    • 1970-01-01
    • 2017-09-29
    • 2019-09-07
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    相关资源
    最近更新 更多