如何使用Python获取APS报告的S3存储文件?无法识别桶名
解决方法
1. 识别S3桶名
S3路径格式为 s3://<桶名>/<对象路径>,你给出的路径里,桶名就是aps-reporting-entweb,剩余部分aps-download-publisher-loleilololailo/reportId=workingonsaturdaystastesgood/executionDate=theday/是桶内的对象前缀路径。
2. Python获取报告的两种实现方式
方式一:使用AWS官方Python SDK(boto3)
这是更推荐的Python原生方案,无需调用外部命令:
- 先安装依赖:
pip install boto3 - 代码示例:
import boto3 # 初始化S3客户端 s3_client = boto3.client('s3') # 定义桶名和目标前缀 bucket_name = 'aps-reporting-entweb' target_prefix = 'aps-download-publisher-loleilololailo/reportId=workingonsaturdaystastesgood/executionDate=theday/' # 列出前缀下的所有文件并批量下载 response = s3_client.list_objects_v2(Bucket=bucket_name, Prefix=target_prefix) for item in response.get('Contents', []): object_key = item['Key'] # 本地保存文件名取路径最后一段 local_filename = object_key.split('/')[-1] s3_client.download_file(bucket_name, object_key, local_filename) print(f"已下载文件:{local_filename}") # 若知道具体文件名,可直接下载单个文件 # s3_client.download_file(bucket_name, f"{target_prefix}具体报告文件名", "本地保存文件名")
方式二:用os.system调用AWS CLI
你提到的方式可行,但需确保本地已配置好AWS CLI(拥有该S3路径的访问权限):
- 代码示例:
import os # 下载单个文件(替换为实际文件名) os.system('aws s3 cp s3://aps-reporting-entweb/aps-download-publisher-loleilololailo/reportId=workingonsaturdaystastesgood/executionDate=theday/具体报告文件名 ./本地保存目录/') # 递归下载前缀下所有文件 os.system('aws s3 cp s3://aps-reporting-entweb/aps-download-publisher-loleilololailo/reportId=workingonsaturdaystastesgood/executionDate=theday/ ./本地保存目录/ --recursive')
内容的提问来源于stack exchange,提问作者error404
相关产品推荐
相关产品推荐

