【问题标题】:How to extract data from grib files in AWS without downloading?如何在不下载的情况下从 AWS 中的 grib 文件中提取数据?
【发布时间】:2021-08-22 03:42:37
【问题描述】:

我正在寻找访问 grib 文件以从云中提取参数(例如温度等),而无需将文件存储在本地。我听说这可以使用 cfgrib API 完成,但找不到任何示例文档(我查看了源文档 here,但这不包括任何在云中访问的内容)。

根据使用 pygrib 的经验,我知道 API 以字节表示形式读取 grib 文件,而 cfgrib 似乎以类似方式处理它。经过一些研究和反复试验,我想出了这段代码,它试图读取文件的字节字符串表示:

导入 boto3 进口博托 从 botocore.config 导入配置 从 botocore 导入 UNSIGNED 导入pygrib 导入cfgrib

if __name__ == '__main__':
    # Define boto config
    my_config = Config(
    signature_version = UNSIGNED,
    retries = {
        'max_attempts': 10,
        'mode': 'standard'
        }
    )
    
    session = boto3.Session(profile_name='default')
    s3 = session.resource('s3')
    my_bucket = s3.Bucket('nbmdata')
    
    # Get a unique key for each file in s3
    file_keys = []
    for my_bucket_object in my_bucket.objects.all():
        file_keys.append(my_bucket_object.key)
    
    # Extract each file as a binary string (without downloading)
    grib_files = []
    for key in file_keys:
        s3 = boto.connect_s3()
        bucket = s3.lookup('bucket') # Removed bucket name
        key = bucket.lookup(key)
        your_bytes = key.get_contents_as_string(headers={'Range' : 'bytes=73-1024'})
        grib_files.append(your_bytes)
     
    # Interpret binary string into pygrib
    for grib_file in grib_files:
        grbs = pygrib.open(grib_file)

这似乎几乎可以工作。我收到此错误:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0xee in position 7: invalid continuation byte

当我尝试用 cfgrib 换掉它时,我得到了同样的错误。我在这里错过了什么?

【问题讨论】:

  • 扎克,你让它工作了吗?

标签: python amazon-web-services boto3 pygrib cfgrib


【解决方案1】:

我知道您正在使用 boto 来使用特定的 get_contents_as_string 方法,但是如果您只是想获取字节,这会起作用吗?我认为 bot 方法正在尝试解码为 utf-8,所以也许您需要指定 encoding=None 来获取字节数组???

但在 boto3 中,我使用它而不解码文件流,然后打印每个文件的前 50 个字符。

grib_files = []
for key in file_keys:
    response = boto3.client('s3').get_object(Bucket='nbmdata', Key=key)
    grib_files.append(response['Body'].read())

for grib in grib_files:
    print(grib[0:50])

b'GRIB\x00\x00\x00\x02\x00\x00\x00\x00\x00\x16\xa7\x7f\x00\x00\x00\x15\x01\x00\x07\x00\x0e\x01\x01\x01\x07\xe5\x05\x1b\x03\x00\x00\x00\x01\x00\x00\x00Q\x03\x00\x009$\xc5\x00\x00\x00'
b'GRIB\x00\x00\x00\x02\x00\x00\x00\x00\x00\x16\x8b\xa8\x00\x00\x00\x15\x01\x00\x07\x00\x0e\x01\x01\x01\x07\xe5\x05\x1b\x03\x00\x00\x00\x01\x00\x00\x00Q\x03\x00\x009$\xc5\x00\x00\x00'

如果您尝试使用 utf-8 对这些内容进行解码,则会引发与您收到的相同的错误。从这里开始,我不知道如何解码和处理,所以也许这有帮助????

【讨论】:

  • 确定阅读内容是一个开始。似乎有几种方法可以做到这一点。真的需要一种方法来阅读这个。 Pygrib 尝试过,但可怕地超时。
猜你喜欢
  • 2020-08-27
  • 1970-01-01
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 2021-02-16
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
相关资源
最近更新 更多