我希望访问一个grib文件,以便从云中提取参数(如温度等),而不必将文件存储在本地。我听说cfgrib API可以做到这一点,但找不到任何示例文档(我查看了源代码文档here,但这不包括任何用于在云中访问的内容)。
从使用pygrib的经验来看,我知道API以字节的形式读取grib文件,而cfgrib似乎也是这样处理的。经过一些研究和尝试,我想出了这个代码,它试图读取文件的字节字符串表示:
导入boto3从botocore.config导入配置从botocore导入无符号导入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交换它时,我得到了同样的错误。这里我漏掉了什么?
发布于 2021-06-04 13:16:21
我知道您正在使用boto来使用那个特定的get_contents_as_string方法,但是如果您只是尝试获取字节数,那么这个方法可以吗?我认为机器人方法正在尝试解码为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解码这些代码,它会抛出与您收到的错误相同的错误。从这里开始,我不知道如何解码和处理,所以这可能会有帮助?
https://stackoverflow.com/questions/67831245
复制相似问题