【问题标题】:How to read binary file on S3 using boto?如何使用 boto 在 S3 上读取二进制文件?
【发布时间】:2017-04-18 17:58:04
【问题描述】:

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

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

 FileURL='URL of the File hosted in S3 Private folder'
 exec(FileURL)
 run(FileURL)

【问题讨论】:

    标签: python amazon-s3 amazon-ec2 boto


    【解决方案1】:

    我不确定我是否理解了您的问题,但这里有一个基于我如何解释您的问题的答案。只要您知道 bucket 名称object/key name,您就可以使用 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'])
    

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

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-04-21
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多