获取所有可用的bucket并打印,但只能使用bucket nam

2024-09-28 17:00:47 发布

您现在位置:Python中文网/ 问答频道 /正文

Im显示所有可用的bucket,代码如下,Im得到以下结果:

<Bucket: test>

但是你知道它是否可能只有这个结果(没有<Bucket...>,比如:

测试

import boto
from boto.s3.connection import S3Connection
s3 = boto.connect_s3()  
buckets = s3.get_all_buckets() 
for key in buckets:
    print key

Tags: key代码fromtestimportgts3bucket
2条回答

我今天写了这个示例代码,来测试一些东西……您可能会发现它也很有用。这假设您有权执行S3函数或列出特定的bucket:

import boto3
import time
import sys

print ("S3 Listing at %s" % time.ctime())
s3 = boto3.client('s3');

def showSingleBucket( bucketName ):
  "Displays the contents of a single bucket"
  if ( len(bucketName) == 0 ):
    print ("bucket name not provided, listing all buckets....") 
    time.sleep(8)
  else:
    print ("Bucket Name provided is: %s" % bucketName)
    s3bucket = boto3.resource('s3')
    my_bucket = s3bucket.Bucket(bucketName)
    for object in my_bucket.objects.all():
      print(object.key)
  return

def showAllBuckets():
  "Displays the contents of S3 for the current account"
  try:
    # Call S3 to list current buckets
    response = s3.list_buckets()
    for bucket in response['Buckets']:
      print (bucket['Name']) 
  except ClientError as e:
    print("The bucket does not exist, choose how to deal with it or raise the exception: "+e)
  return

if ( len(sys.argv[1:]) != 0 ):
  showSingleBucket(''.join(sys.argv[1]))
else:
  showAllBuckets()
import boto
from boto.s3.connection import S3Connection
s3 = boto.connect_s3()  
buckets = s3.get_all_buckets() 
for key in buckets:
    print key.name

这应该管用。。键.名称

相关问题 更多 >