[docs]classOasisBaseCommand(BaseCommand):""" The base command to inherit from for each command. 2 additional arguments (``--verbose`` and ``--config``) are added to the parser so that they are available for all commands. """def__init__(self,*args,**kwargs):self._logger=None
[docs]defadd_args(self,parser):""" Adds arguments to the argument parser. This is used to modify which arguments are processed by the command. 2 global parameters (``--verbose`` and ``--config``) are added so that they are available to all commands. :param parser: The argument parser object :type parser: ArgumentParser """parser.add_argument('-V','--verbose',action='store_true',help='Use verbose logging.')parser.add_argument('-C','--config',required=False,type=PathCleaner('MDK config. JSON file',preexists=True),help='MDK config. JSON file',default='./oasislmf.json'ifos.path.isfile('./oasislmf.json')elseNone)
[docs]defparse_args(self):""" Parses the command line arguments and sets them in ``self.args`` :return: The arguments taken from the command line """try:self.args=super(OasisBaseCommand,self).parse_args()self.log_verbose=self.args.verboseself.setup_logger()returnself.argsexceptException:self.setup_logger()raise
[docs]defsetup_logger(self):""" The logger to use for the command with the verbosity set """ifnotself._logger:ifself.log_verbose:log_level=logging.DEBUGlog_format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'else:log_level=logging.INFOlog_format='%(message)s'logger=logging.getLogger('oasislmf')forhandlerinlist(logger.handlers):ifhandler.name=='oasislmf':logger.removeHandler(handler)breakods_logger=logging.getLogger('ods_tools')ifself.log_verbose:ods_logger.setLevel(logging.DEBUG)else:ods_logger.setLevel(logging.WARNING)ods_logger.propagate=Falsech=logging.StreamHandler(stream=sys.stdout)ch.name='oasislmf'ch.setFormatter(logging.Formatter(log_format))logger.addHandler(ch)ods_logger.addHandler(ch)logger.setLevel(log_level)self._logger=logger
[docs]classOasisComputationCommand(OasisBaseCommand):""" Eventually, the Parent class for all Oasis Computation Command create the command line interface from parameter define in the associated computation step """
[docs]defadd_args(self,parser):""" Adds arguments to the argument parser. :param parser: The argument parser object :type parser: ArgumentParser """super().add_args(parser)forparaminom.computations_params[self.computation_name]:add_argument_kwargs={key:param.get(key)forkeyin['action','nargs','const','type','choices','help','metavar','dest']ifparam.get(key)isnotNone}# If 'Help' is not set then this is a function only paramter, skipif'help'inadd_argument_kwargs:arg_name=f"--{param['name'].replace('_','-')}"ifparam.get('flag'):parser.add_argument(param.get('flag'),arg_name,**add_argument_kwargs)else:parser.add_argument(arg_name,**add_argument_kwargs)
[docs]defaction(self,args):""" Generic method that call the correct manager method from the child class computation_name :param args: The arguments from the command line :type args: Namespace """inputs=InputValues(args)_kwargs={param['name']:inputs.get(param['name'],required=param.get('required'),is_path=param.get('is_path'),dtype=param.get('type'))forparaminom.computations_params[self.computation_name]}# Override logger setup from kwargsif'verbose'in_kwargs:self.logger.level=logging.DEBUGifstr2bool(_kwargs.get('verbose'))elselogging.INFOself.logger.info(f'\nStating oasislmf command - {self.computation_name}')manager_method=getattr(om(),om.computation_name_to_method(self.computation_name))manager_method(**_kwargs)