如何使用boto读取S3上的二进制文件?

Ten*_*sor 5 python amazon-s3 amazon-ec2 boto

我在 S3 文件夹(私人部分)中有一系列 Python 脚本/Excel 文件。如果它们是公开的,我可以通过 HTTP URL 读取访问它们。

想知道如何以二进制形式访问它们以执行它们?

 FileURL='URL of the File hosted in S3 Private folder'
 exec(FileURL)
 run(FileURL)
Run Code Online (Sandbox Code Playgroud)

NYC*_*yes 3

我不完全确定我理解你的问题,但这里有一个基于我如何解释你的问题的答案。只要您知道您的存储桶名称对象/键名称,您就可以使用boto3执行以下操作(也许也可以使用 boto,尽管我不确定):

#! /usr/bin/env python3
#
import boto3
from botocore.exceptions import ClientError

s3_bucket   = 'myBucketName'
s3_key      = 'myFileName' # Can be a nested key/file.
aws_profile = 'IAM-User-with-read-access-to-bucket-and-key'
aws_region  = 'us-east-1'

aws_session  = boto3.Session(profile_name = aws_profile)
s3_resource  = aws_session.resource('s3', aws_region)
s3_object    = s3_resource.Bucket(s3_bucket).Object(s3_key)

# In case nested key/file, get the leaf-name and use that as our local file name.
basename = s3_key.split('/')[-1].strip()
tmp_file = '/tmp/' + basename
try:
   s3_object.download_file(tmp_file) # Not .download_fileobj()
except ClientError as e:
   print("Received error: %s", e, exc_info=True)
   print("e.response['Error']['Code']: %s", e.response['Error']['Code'])
Run Code Online (Sandbox Code Playgroud)

顺便说一下,您可以从您的 PUBLIC URL 添加 Python 语句以从中解析出存储桶名称和键/对象名称。

我希望这有帮助。