2011-02-14 115 views
16

我想写一个Python脚本,将阅读和S3使用写文件的网址,如:“S3,/ mybucket /文件”。它需要在本地运行而不需要更改任何代码。有没有办法做到这一点?如何使用URL访问Python中的s3文件?

编辑:这里有一些很好的建议,但我真正想要的是什么,让我做这件事:

myfile = open("s3://mybucket/file", "r") 

,然后使用该文件对象像任何其他文件对象。那真的很酷。如果不存在,我可能会为自己写这样的内容。我可以在simples3或boto上构建该抽象层。

+0

你需要的文件是私有的或者只是最简单的情况? – 2011-02-15 15:29:08

+0

他们不需要是私人的。我只是想能够使用URL在我的代码中访问它们。我想我真正需要的是一个抽象层,允许我使用的URL文件的工作,不管是一个Python库或类似保险丝的东西,但它支持的URL,而不是本地文件路径。 – 2011-02-15 18:50:18

回答

2

我还没有看到的东西,会直接与S3网址的工作,但你可以使用一个S3 access librarysimples3看起来体面的)和一些简单的字符串操作:

>>> url = "s3:/bucket/path/" 
>>> _, path = url.split(":", 1) 
>>> path = path.lstrip("/") 
>>> bucket, path = path.split("/", 1) 
>>> print bucket 
'bucket' 
>>> print path 
'path/' 
+0

这就是我在想什么。除了解决s3路径外,可能还有一些额外的例程来抽象读取/写入桶。 – 2011-02-15 18:55:43

1

可以使用Boto Python API通过访问S3蟒蛇。它是一个好的图书馆。在此之后的Boto安装,下面的示例PROGRAME会为你工作

>>> k = Key(b) 
>>> k.key = 'yourfile' 
>>> k.set_contents_from_filename('yourfile.txt') 

您可以在这里找到更多的信息http://boto.cloudhackers.com/s3_tut.html#storing-data

+0

的问题实际上是关于使用的URL开始S3://与否(本地文件),因此,S3和一个本地文件系统可以在由Python程序以统一的方式来访问。 – EOL 2015-04-02 03:33:59

10

打开,它应该是这么简单:

import urllib 
opener = urllib.URLopener() 
myurl = "https://s3.amazonaws.com/skyl/fake.xyz" 
myfile = opener.open(myurl) 

这将S3工作,如果该文件是公开的。

编写使用博托一个文件,它会有点像这样:

from boto.s3.connection import S3Connection 
conn = S3Connection(AWS_KEY, AWS_SECRET) 
bucket = conn.get_bucket(BUCKET) 
destination = bucket.new_key() 
destination.name = filename 
destination.set_contents_from_file(myfile) 
destination.make_public() 

还是让我知道这对你的作品:)

3

Here's how they doawscli

def find_bucket_key(s3_path): 
    """ 
    This is a helper function that given an s3 path such that the path is of 
    the form: bucket/key 
    It will return the bucket and the key represented by the s3 path 
    """ 
    s3_components = s3_path.split('/') 
    bucket = s3_components[0] 
    s3_key = "" 
    if len(s3_components) > 1: 
     s3_key = '/'.join(s3_components[1:]) 
    return bucket, s3_key 


def split_s3_bucket_key(s3_path): 
    """Split s3 path into bucket and key prefix. 
    This will also handle the s3:// prefix. 
    :return: Tuple of ('bucketname', 'keyname') 
    """ 
    if s3_path.startswith('s3://'): 
     s3_path = s3_path[5:] 
    return find_bucket_key(s3_path) 

,你可以只用代码使用这样

from awscli.customizations.s3.utils import split_s3_bucket_key 
import boto3 
client = boto3.client('s3') 
bucket_name, key_name = split_s3_bucket_key(
    's3://example-bucket-name/path/to/example.txt') 
response = client.get_object(Bucket=bucket_name, Key=key_name) 

这并没有解决与S3键为file like object交互的目标,但它是在该方向迈出的一步。