I want to pass a file (netCDF data file) as first argument and an option (-v) to indicate the variable(s) to read from this file to my script.
I figured I'd need a custom callback to evaluate if this or these variable(s) is/are contained in the file. However, I'm stuck figuring out how to access the argument from within my callback method.
import click
import xarray as xr
def validate_variable(ctx, param, value):
"""Check that requested variable(s) are in netCDF file """
# HOW TO ACCESS ARGUMENT 'tile' ???
with xr.open_dataset(ctx.tile) as ds:
for v in value:
if v not in ds.data_vars:
raise click.BadParameter('Var %s not in file %s.' % (v, ctx.tile))
EPILOG = 'my script ...'
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS, epilog=EPILOG)
@click.pass_context
@click.option('--variable', '-v', multiple=True, metavar='VAR',
callback=validate_variable,
help='variable to render')
@click.argument('tile', type=click.File())
def cli(tile, variable):
main(tile, variable)