[docs]classApplication:""" Represents an application to be executed. Parameters ---------- app : Union[Path, Callable] The application to be executed. It can be either a file path or a callable object. config : ConfigParser The configuration object containing application settings. args : tuple, optional Positional arguments to be passed to the application (default is an empty tuple). kwargs : Dict, optional Keyword arguments to be passed to the application (default is an empty dictionary). Attributes ---------- name : str The name of the application. args : tuple The positional arguments to be passed to the application. kwargs : Dict The keyword arguments to be passed to the application. Methods ------- run() Executes the application. """def__init__(self,app:Union[Path,Callable,str],config:ConfigParser,is_binary:bool=False,args:Tuple[Any,...]=(),kwargs:Dict[str,Any]={},):self._app=appself._name=self._setName(config)self._args=argsself._kwargs=kwargsself._is_binary=is_binaryifisinstance(app,Path):try:withopen(app,"r")asscriptFile:self._scriptFile=scriptFile.read()exceptFileNotFoundError:log.error(f"perun could not find the file {app}. Please check the path.")exit()@propertydefname(self)->str:"""Return the application name."""returnself._name@propertydefargs(self)->Tuple[Any,...]:"""Return the application positional arguments."""returnself._args@propertydefkwargs(self)->Dict[str,Any]:"""Return the application keyword arguments."""returnself._kwargs@propertydefis_binary(self)->bool:"""Return the application keyword arguments."""returnself._is_binarydef_setName(self,config:ConfigParser)->str:""" Return the application name based on the configuration and application path. Parameters ---------- config : ConfigParser The configuration object containing application settings. Returns ------- str The application name. """app_name=config.get("output","app_name")ifapp_nameandapp_name!="SLURM":returnapp_nameelif(app_nameandapp_name!="SLURM"and"SBATCH_JOB_NAME"inos.environandapp_name=="SLURM"):returnos.environ["SBATCH_JOB_NAME"]elifisinstance(self._app,Path):returnself._app.stemelifcallable(self._app):returnself._app.__name__elifisinstance(self._app,str):returnself._appelse:raiseValueError("Application name not found")def_cleanup(self)->None:foriinrange(3):gc.collect(i)
[docs]defrun(self)->Any:""" Execute the application. If callable, returns the function result. Raises ------ ValueError If the application is not found. """ifself._is_binaryandisinstance(self._app,str):subprocess.run([self._app,*self._args],env=os.environ)elifisinstance(self._app,Path):exec(self._scriptFile,{"__name__":"__main__","__file__":self.name},)self._cleanup()elifcallable(self._app):result=self._app(*self._args,**self._kwargs)self._cleanup()returnresultelse:raiseValueError("Application not found")
def__str__(self)->str:"""Return the application name."""returnf"{self.name}"def__repr__(self)->str:"""Return the application name."""returnf"Application({self.name})"