# coding=utf-8 from earthdiagnostics.utils import Utils import os from bscearth.utils.log import Log import six class CDFTools(object): """ Class to run CDFTools executables :param path: path to CDFTOOLS binaries :type path: str """ def __init__(self, path=''): self.path = path # noinspection PyShadowingBuiltins def run(self, command, input, output=None, options=None, log_level=Log.INFO, input_option=None): """ Runs one of the CDFTools :param command: executable to run :type command: str | iterable :param input: input file :type input: str :param output: output file. Not all tools support this parameter :type options: str :param options: options for the tool. :type options: str | list[str] | Tuple[str] :param log_level: log level at which the output of the cdftool command will be added :type log_level: int :param input_option: option to add before input file :type input_option: str """ line = [os.path.join(self.path, command)] self._check_command_existence(line[0]) if input_option: line.append(input_option) self._check_input(command, input, line) if options: if isinstance(options, six.string_types): options = options.split() for option in options: line.append(str(option)) if output: if input == output: raise ValueError('Input and output file can not be the same on CDFTools') line.append('-o') line.append(output) Log.debug('Executing {0}', ' '.join(line)) shell_output = Utils.execute_shell_command(line, log_level) self._check_output_was_created(line, output) return shell_output @staticmethod def _check_output_was_created(line, output): if output: if not os.path.exists(output): raise Exception('Error executing {0}\n Output file not created', ' '.join(line)) # noinspection PyShadowingBuiltins @staticmethod def _check_input(command, input, line): if input: if isinstance(input, six.string_types): line.append(input) if not os.path.exists(input): raise ValueError('Error executing {0}\n Input file {1} file does not exist', command, input) else: for element in input: line.append(element) if not os.path.exists(element): raise ValueError('Error executing {0}\n Input file {1} file does not exist', command, element) # noinspection PyMethodMayBeStatic def is_exe(self, fpath): return os.path.isfile(fpath) and os.access(fpath, os.X_OK) def _check_command_existence(self, command): if self.path: if self.is_exe(os.path.join(self.path, command)): return else: for path in os.environ["PATH"].split(os.pathsep): path = path.strip('"') exe_file = os.path.join(path, command) if self.is_exe(exe_file): return raise ValueError('Error executing {0}\n Command does not exist in {1}', command, self.path)