【问题标题】:What is the boto3 equivalent of aws s3 ls?aws s3 ls 的 boto3 等价物是什么?
【发布时间】:2022-01-04 19:17:59
【问题描述】:

我正在尝试使用 boto3 复制命令 aws s3 ls s3://bucket/prefix/。目前,我可以使用

抓取路径中的所有对象
s3 = boto3.client('s3')

bucket = "my-bucket"
prefix = "my-prefix"
paginator = s3.get_paginator('list_objects_v2')
page_iterator = paginator.paginate(Bucket=bucket, Prefix = prefix)

然后,我可以遍历 page_iterator 并手动重建该路径中的顶级目录。但是,由于路径中有大量对象,检索所有对象以重建此命令的结果对我来说大约需要 30 秒,而 AWS CLI 命令几乎是即时的。有没有更有效的方法来做到这一点?

【问题讨论】:

    标签: amazon-s3 boto3 aws-cli


    【解决方案1】:

    您应该使用list_objects_v2Delimiter 选项将具有公共前缀的任何对象组合在一起。这基本上是 aws s3 ls 在没有 --recursive 开关的情况下所做的:

    import boto3
    s3 = boto3.client('s3')
    bucket = "my-bucket"
    prefix = "my-prefix"
    
    paginator = s3.get_paginator('list_objects_v2')
    
    # List all objects, group objects with a common prefix
    for page in paginator.paginate(Bucket=bucket, Prefix=prefix, Delimiter="/"):
        # CommonPrefixes and Contents might not be included in a page if there
        # are no items, so use .get() to return an empty list in that case
        for cur in page.get("CommonPrefixes", []):
            print("<PRE> " + cur["Prefix"])
        for cur in page.get("Contents", []):
            print(cur["Size"], cur["Key"])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 2014-05-08
      • 2014-06-12
      • 1970-01-01
      • 2022-11-28
      • 1970-01-01
      • 2018-07-10
      相关资源
      最近更新 更多