You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python SDK从S3下载文件遇到空桶等运行错误求助

代码存在的核心问题

  • 缩进逻辑错误:else: print('Bucket is empty')错误和下载判断逻辑对齐,本该对应obj_count > 0的判断分支,当桶内无对象时object_to_copy_index未定义会直接报错,桶内有对象时也会误触发空桶提示
  • 下载返回值判断错误:boto3的s3.download_file方法执行成功返回None,你写的if s3_handle.download_file(...)判断永远为假,无法触发成功日志,逻辑完全错误
  • 日志变量错误:日志里使用的obj["Key"]是遍历桶对象时的临时变量,最终只会指向最后一个遍历到的对象,不是你选中下载的文件
  • 输入无校验:用户输入的索引如果不是合法数字、或者超出对象列表范围,直接转int会触发异常
  • 无异常捕获:权限不足、网络故障、对象不存在等问题都会直接终止程序

修正后的代码

import logging
import botocore

# 提前配置logging,否则info日志不会输出
logging.basicConfig(level=logging.INFO)

def function_for_f(s3_handle=None):
    ## 列举存储桶并选择
    selected_bucket_name_origin = select_buckets(s3_handle=s3_handle)
    print(f"Selected bucket was: {selected_bucket_name_origin}")
    # 拉取桶内对象列表
    objects = list_bucket_objects_aws(s3_handle=s3_handle, bucket_name=selected_bucket_name_origin)
    
    if objects is None or len(objects) == 0:
        print('Bucket is empty')
        return
    
    # 打印可选对象列表
    for idx, obj in enumerate(objects):
        print(f'{idx}. {obj["Key"]}')
    
    # 校验用户输入
    while True:
        input_val = input('Which object to copy?')
        try:
            object_to_copy_index = int(input_val)
            if 0 <= object_to_copy_index < len(objects):
                break
            else:
                print(f"请输入0到{len(objects)-1}之间的数字")
        except ValueError:
            print("请输入合法的数字索引")
    
    selected_key = objects[object_to_copy_index]["Key"]
    print(f'Downloading {selected_key}')
    
    # 执行下载加异常捕获
    try:
        s3_handle.download_file(selected_bucket_name_origin, selected_key, '1.txt')
        logging.info(f'{selected_key} was downloaded from {selected_bucket_name_origin}')
    except botocore.exceptions.ClientError as e:
        if e.response['Error']['Code'] == "404":
            print("The object does not exist.")
        else:
            print(f"下载出错:{str(e)}")
            raise

内容的提问来源于stack exchange,提问作者Sergey V.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:15:04