要读取.nc
文件,Iris 在内部使用您提到的相同库。netcdf4-python
这意味着理论上您可以:
子类CFReader覆盖它的__init__
方法,唯一的变化是行self._dataset = netCDF4.Dataset(self._filename, mode='r')
编写您自己的load_cube
函数(基于此代码)将使用您的自定义 CFReader,或者您可以使用自定义的 CFReaderiris
进行猴子补丁。
猴子修补的一般想法:
from urllib.request import urlopen
import iris.fileformats.cf
import netCDF4 as nc
def __patch_CFReader():
if getattr(iris.fileformats.cf.CFReader, '_HACKY_PATCHED'):
return
from iris.fileformats.cf import CFReader
class CustomCFReader(CFReader):
_HACKY_PATCHED = True
def __init__(self, uri, *args, **kwargs):
# ... other code copied
with urlopen(url) as stream:
self._dataset = nc.Dataset('HadCRUT', memory=stream.read())
# ... other code copied
iris.fileformats.cf.CFReader = CustomCFReader
__patch_CFReader()
import iris
cube = iris.load_cube('https://crudata.uea.ac.uk/cru/data/temperature/HadCRUT.4.6.0.0.median.nc')
警告!根据您的项目中导入的方式,猴子补丁可能并不总是像您最初想象的那样工作。所以也许你应该更喜欢使用一些专门为猴子补丁设计的库,例如大猩猩:
https://gorilla.readthedocs.io/en/latest/tutorial.html
# my_patches.py:
from urllib.request import urlopen
import gorilla
import iris.fileformats.cf
import netCDF4 as nc
settings = gorilla.Settings(allow_hit=True)
@gorilla.patch(iris.fileformats.cf.CFReader, settings=settings)
def __init__(self, uri, *args, **kwargs):
# ... other code copied
with urlopen(url) as stream:
self._dataset = nc.Dataset('HadCRUT', memory=stream.read())
# ... other code copied
# earliest_imported_module.py:
import gorilla
import my_patches
for patch in gorilla.find_patches([my_patches]):
gorilla.apply(patch)