2011-02-14 116 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交互的目標,但它是在該方向邁出的一步。