43

ファイルを S3 から Cloudfiles にコピーしていますが、ファイルをディスクに書き込もうとはしません。Python-Cloudfiles ライブラリには、私が必要としているように見える object.stream() 呼び出しがありますが、boto で同等の呼び出しが見つかりません。私は次のようなことができることを願っています:

shutil.copyfileobj(s3Object.stream(),rsObject.stream())

これは boto (または他の s3 ライブラリと思われます) で可能ですか?

4

5 に答える 5

22

S3 の on オブジェクトを表す boto の Key オブジェクトは、イテレータのように使用できるため、次のようなことができるはずです。

>>> import boto
>>> c = boto.connect_s3()
>>> bucket = c.lookup('garnaat_pub')
>>> key = bucket.lookup('Scan1.jpg')
>>> for bytes in key:
...   write bytes to output stream

または、あなたの例の場合のように、次のことができます:

>>> shutil.copyfileobj(key, rsObject.stream())
于 2011-10-02T07:54:34.523 に答える
21

この質問を見ている人の少なくとも一部は私のようなもので、boto から 1 行ずつ (またはカンマごと、またはその他の区切り記号で) ファイルをストリーミングする方法を望んでいると思います。これを行う簡単な方法は次のとおりです。

def getS3ResultsAsIterator(self, aws_access_info, key, prefix):        
    s3_conn = S3Connection(**aws_access)
    bucket_obj = s3_conn.get_bucket(key)
    # go through the list of files in the key
    for f in bucket_obj.list(prefix=prefix):
        unfinished_line = ''
        for byte in f:
            byte = unfinished_line + byte
            #split on whatever, or use a regex with re.split()
            lines = byte.split('\n')
            unfinished_line = lines.pop()
            for line in lines:
                yield line

上記の@garnaatの答えは依然として素晴らしく、100%真実です。うまくいけば、私のものはまだ誰かを助けます。

于 2013-06-03T04:29:35.220 に答える
12

Botocore'sStreamingBodyにはiter_lines()メソッドがあります:

https://botocore.amazonaws.com/v1/documentation/api/latest/reference/response.html#botocore.response.StreamingBody.iter_lines

そう:

import boto3
s3r = boto3.resource('s3')
iterator = s3r.Object(bucket, key).get()['Body'].iter_lines()

for line in iterator:
    print(line)
于 2018-08-31T19:28:23.257 に答える
7

これは、ストリーミングボディをラップする私のソリューションです:

import io
class S3ObjectInterator(io.RawIOBase):
    def __init__(self, bucket, key):
        """Initialize with S3 bucket and key names"""
        self.s3c = boto3.client('s3')
        self.obj_stream = self.s3c.get_object(Bucket=bucket, Key=key)['Body']

    def read(self, n=-1):
        """Read from the stream"""
        return self.obj_stream.read() if n == -1 else self.obj_stream.read(n)

使用例:

obj_stream = S3ObjectInterator(bucket, key)
for line in obj_stream:
    print line
于 2016-11-28T22:26:10.360 に答える