Source code for pycaps.diagnostic.listvars
#!/usr/bin/env python2.7
#Code: listvars.py (Python Script)
#Author: Nate Snook (CASA/CAPS/SoM)
#Written: Mar. 2008
#Modification History:
# 19 Feb. 2014 -- Nate Snook (added netcdf support, updated script to use argparse)
# 14 Aug. 2014 -- Nate Snook (added generic case for when no format is specified)
# 24 Sept. 2015 --Nate Snook (added output of dimensions)
# 5 Oct. 2015 -- Nate Snook (no need to specify NetCDF explicitly; handled via try/except)
# 11 Nov. 2015 -- Nate Snook (Converted from stand-alone script to function for pycaps)
from PyNIO import Nio
from mpl_toolkits.basemap import Basemap
[docs]def listvars(source, shapefile=False):
"""
Gives a list of the variables, attributes, and dimensions contained in a
NetCDF or HDF file. If called with shapefile = True, it will instead provide
information on variables contained in a shapefile.
Args:
source: The file whose contents you wish to list (for best results, give full path)
shapefile: OPTIONAL -- If shapefile = True, listvars will attempt to open the source as a shapefile and give relevant information about the contents.
Returns:
<<nothing>> (prints information about file contents to the terminal window)
"""
#----------------------------------------------------#
if shapefile == True:
#provide an arbitrary map specification to allow for shapefile reading
map=Basemap(projection='cyl', llcrnrlat=32, urcrnrlat=40, llcrnrlon=-100, urcrnrlon=-80,resolution='c')
map.readshapefile(source, 'contents', drawbounds=True)
print '------------------------------------'
print 'Number of shapes contained in ' + str(source) + ': ' + str(len(map.contents))
for index, shape in enumerate(map.contents):
print ' Shape #' + str(index) + ' contents: ' + str(map.contents[index])
for key_num, key in enumerate(map.contents_info[index].keys()):
print ' ' + str(key) + ': ' + str(map.contents_info[index].values()[key_num])
print ' -- -- -- -- -- -- -- --'
else:
try:
testfile = Nio.open_file(source, mode='r', options=None, history='', format='netcdf')
filefmt = 'NetCDF'
except:
try:
testfile = Nio.open_file(source, mode='r', options=None, history='', format='hdf')
filefmt = 'HDF'
except:
print 'Attempts to open using NetCDF and HDF format failed... trying generic format...'
testfile = Nio.open_file(source, mode='r', options=None, history='')
filefmt = 'Unknown'
print '--------------------------------------'
print 'File format: ' + str(filefmt)
print '--------------------------------------'
varnames = testfile.variables.keys()
print 'Listing of variables stored in ' + str(source)
print varnames
print '--------------------------------------'
attrnames = testfile.attributes.keys()
print 'Listing of attributes stored in ' + str(source)
print attrnames
print '--------------------------------------'
dimnames = testfile.dimensions.keys()
print 'Listing of dimensions stored in ' + str(source)
print dimnames
print '--------------------------------------'