def result(self, timeout=None): """ Get the MatlabEngine object or the result of a MATLAB statement. Parameter timeout: int Number of seconds to wait before returning. By default, this function will wait until the result is generated. Returns The MatlabEngine object or the result of MATLAB statement. A tuple is returned if multiple outputs are returned. Raises SyntaxError - if there is an error in the MATLAB statement. InterruptedError - if the task is interrupted. CancelledError - if the evaluation of MATLAB function is cancelled already. TimeoutError - if this method fails to get the result in timeout seconds. MatlabExecutionError - if the MATLAB statement fails in execution. TypeError - if the data type of return value is not supported. RejectedExecutionError - an error occurs if the engine is terminated. """ if timeout is not None: if not isinstance(timeout, (int, long, float)): raise TypeError(pythonengine.getMessage('TimeoutMustBeNumeric') + " %s" % type(timeout).__name__) if timeout < 0: raise TypeError(pythonengine.getMessage('TimeoutCannotBeNegative')) return self.__future.result(timeout)
def result(self, timeout=None): """ Get the MatlabEngine object or the result of a MATLAB statement. Parameter timeout: int Number of seconds to wait before returning. By default, this function will wait until the result is generated. Returns The MatlabEngine object or the result of MATLAB statement. A tuple is returned if multiple outputs are returned. Raises SyntaxError - if there is an error in the MATLAB statement. InterruptedError - if the task is interrupted. CancelledError - if the evaluation of MATLAB function is cancelled already. TimeoutError - if this method fails to get the result in timeout seconds. MatlabExecutionError - if the MATLAB statement fails in execution. TypeError - if the data type of return value is not supported. RejectedExecutionError - an error occurs if the engine is terminated. """ if timeout is not None: if not isinstance(timeout, (int, long, float)): raise TypeError( pythonengine.getMessage('TimeoutMustBeNumeric', type(timeout).__name__)) if timeout < 0: raise TypeError( pythonengine.getMessage('TimeoutCannotBeNegative')) return self.__future.result(timeout)
def __validate_identity(self, attr): if not isinstance(attr, str): raise TypeError( pythonengine.getMessage('VarNameMustBeStr', type(attr).__name__)) if not pythonengine.validateIdentity(attr): raise ValueError(pythonengine.getMessage('VarNameNotValid'))
def __call__(self, *args, **kwargs): self.__validate_engine() nargs = kwargs.pop('nargout', 1) if not isinstance(nargs, int): raise TypeError( pythonengine.getMessage('NargoutMustBeInt', type(nargs).__name__)) if nargs < 0: raise ValueError( pythonengine.getMessage('NargoutCannotBeLessThanZero')) _stdout = kwargs.pop('stdout', None) _stderr = kwargs.pop('stderr', None) background = enginehelper._get_async_or_background_argument(kwargs) _sIO_info = '{0}.{1}'.format(sIO.__name__, sIO.StringIO.__name__) if (_stdout is not None) and (not isinstance(_stdout, sIO.StringIO)): _stdout_info = '{0}.{1}'.format(_stdout.__class__.__module__, _stdout.__class__.__name__) raise TypeError( pythonengine.getMessage('StdoutMustBeStringIO', _sIO_info, _stdout_info)) if (_stderr is not None) and (not isinstance(_stderr, sIO.StringIO)): _stderr_info = '{0}.{1}'.format(_stderr.__class__.__module__, _stderr.__class__.__name__) raise TypeError( pythonengine.getMessage('StderrMustBeStringIO', _sIO_info, _stderr_info)) future = pythonengine.evaluateFunction(self._engine()._matlab, self._name, nargs, args, out=_stdout, err=_stderr) if background: return FutureResult(self._engine(), future, nargs, _stdout, _stderr, feval=True) else: return FutureResult(self._engine(), future, nargs, _stdout, _stderr, feval=True).result()
def result(self, timeout=None): """ Get the result of a MATLAB statement. Parameter timeout: int Number of seconds to wait before returning. By default, this function will wait until the result is generated. Returns The result of MATLAB statement. A tuple is returned if multiple outputs are returned. Raises SyntaxError - if there is an error in the MATLAB statement. InterruptedError - if the task is interrupted. CancelledError - if the evaluation of MATLAB function is cancelled already. TimeoutError - if this method fails to get the result in timeout seconds. MatlabExecutionError - if the MATLAB statement fails in execution. TypeError - if the data type of return value is not supported. RejectedExecutionError - an error occurs if the engine is terminated. """ self.__validate_engine() if self._retrieved: return self._result """ Following code is used to poll the Ctrl+C every second from keyboard in order to cancel a MATLAB function. """ try: result_ready = self.wait(timeout, pythonengine.waitForFEval) if not result_ready: raise TimeoutError( pythonengine.getMessage('MatlabFunctionTimeout')) self._result = pythonengine.getFEvalResult(self._future, self._nargout, None, out=self._out, err=self._err) self._retrieved = True return self._result except KeyboardInterrupt: self.cancel() if self.cancelled(): print(pythonengine.getMessage('MatlabFunctionCancelled')) except: raise
def __getitem__(self,attr): self.__validate_engine() if not isinstance(attr, str): raise TypeError(pythonengine.getMessage('VarNameMustBeStr') + " %s" % type(attr).__name__) if not pythonengine.validateIdentity(attr): raise ValueError(pythonengine.getMessage('VarNameNotValid')) _method=MatlabFunc(self._engine(), "matlab.internal.engine.getVariable") future = _method(attr) return future
def result(self, timeout=None): """ Get the MatlabEngine instance. Parameter timeout: Number of seconds to wait before returning. By default, this function will wait until the MatlabEngine instance is ready. Returns An object of MatlabEngine class. Raises CancelledError - if the launch or connection of MATLAB is cancelled already. TimeoutError - if the MATLAB instance is not ready in timeout seconds. """ from matlab.engine import MatlabEngine if self._cancelled: if self._attach: raise CancelledError( pythonengine.getMessage('ConnectMatlabCancelled')) else: raise CancelledError( pythonengine.getMessage('LaunchMatlabCancelled')) if self._matlab is not None: return self._matlab try: result_ready = self.wait(timeout, pythonengine.waitForMATLAB) if not result_ready: if self._attach: raise TimeoutError( pythonengine.getMessage('ConnectMatlabTimeout')) else: raise TimeoutError( pythonengine.getMessage('LaunchMatlabTimeout')) handle = pythonengine.getMATLAB(self._future) eng = MatlabEngine(handle) self._matlab = eng with _engine_lock: _engines.append(weakref.ref(eng)) return eng except KeyboardInterrupt: self.cancel() print(pythonengine.getMessage('MatlabCancelled')) except: raise
def result(self, timeout=None): """ Get the result of a MATLAB statement. Parameter timeout: int Number of seconds to wait before returning. By default, this function will wait until the result is generated. Returns The result of MATLAB statement. A tuple is returned if multiple outputs are returned. Raises SyntaxError - if there is an error in the MATLAB statement. InterruptedError - if the task is interrupted. CancelledError - if the evaluation of MATLAB function is cancelled already. TimeoutError - if this method fails to get the result in timeout seconds. MatlabExecutionError - if the MATLAB statement fails in execution. TypeError - if the data type of return value is not supported. RejectedExecutionError - an error occurs if the engine is terminated. """ self.__validate_engine() if self._retrieved: return self._result """ Following code is used to poll the Ctrl+C every second from keyboard in order to cancel a MATLAB function. """ try: result_ready = self.wait(timeout, pythonengine.waitForFEval) if not result_ready: raise TimeoutError(pythonengine.getMessage('MatlabFunctionTimeout')) self._result = pythonengine.getFEvalResult(self._future,self._nargout, None, out=self._out, err=self._err) self._retrieved = True return self._result except KeyboardInterrupt: self.cancel() if self.cancelled(): print(pythonengine.getMessage('MatlabFunctionCancelled')) except: raise
def __setitem__(self,attr,value): self.__validate_engine() if not pythonengine.validateIdentity(attr): raise ValueError(pythonengine.getMessage('VarNameNotValid')) _method=MatlabFunc(self._engine(), "assignin") return _method("base", attr, value, nargout=0)
def __call__(self, *args, **kwargs): self.__validate_engine() nargs = kwargs.pop('nargout', 1) if not isinstance(nargs, int): raise TypeError(pythonengine.getMessage('NargoutMustBeInt') + ' %s' % type(nargs).__name__) if nargs < 0: raise ValueError(pythonengine.getMessage('NargoutCannotBeLessThanZero')) async = kwargs.pop('async', False) if not isinstance(async, bool): raise TypeError(pythonengine.getMessage('AsyncMustBeBool') + ' %s' % type(async).__name__)
def __call__(self, *args, **kwargs): self.__validate_engine() nargs = kwargs.pop('nargout', 1) if not isinstance(nargs, int): raise TypeError(pythonengine.getMessage('NargoutMustBeInt') + ' %s' % type(nargs).__name__) if nargs < 0: raise ValueError(pythonengine.getMessage('NargoutCannotBeLessThanZero')) async = kwargs.pop('async', False) if not isinstance(async, bool): raise TypeError(pythonengine.getMessage('AsyncMustBeBool') + ' %s' % type(async).__name__)
def _get_async_or_background_argument(kwargs): if 'async' in kwargs and 'background' in kwargs: raise KeyError(pythonengine.getMessage('EitherAsyncOrBackground')) background = False if 'async' in kwargs: background = kwargs.pop('async', False) if not isinstance(background, bool): raise TypeError(pythonengine.getMessage('AsyncMustBeBool')) warnings.warn(pythonengine.getMessage('AsyncWillDeprecate'), DeprecationWarning) if 'background' in kwargs: background = kwargs.pop('background', False) if not isinstance(background, bool): raise TypeError(pythonengine.getMessage('BackgroundMustBeBool')) if kwargs: raise TypeError((pythonengine.getMessage('InvalidKwargs') + ' %r') % (list(kwargs.keys())[0])) return background
def _get_async_or_background_argument(kwargs): if 'async' in kwargs and 'background' in kwargs: raise KeyError(pythonengine.getMessage('EitherAsyncOrBackground')) background = False if 'async' in kwargs: background = kwargs.pop('async', False) if not isinstance(background, bool): raise TypeError(pythonengine.getMessage('AsyncMustBeBool')) if sys.version_info.major >= 3 and sys.version_info.minor >= 7: # No test should be passing "async" with Python 3.7 or higher, so throw an exception # if a test tries to do it. raise SyntaxError(pythonengine.getMessage('AsyncWillDeprecate')) if 'background' in kwargs: background = kwargs.pop('background', False) if not isinstance(background, bool): raise TypeError(pythonengine.getMessage('BackgroundMustBeBool')) if kwargs: raise TypeError( (pythonengine.getMessage('InvalidKwargs', list(kwargs.keys())[0].__repr__()))) return background
def __validate_engine(self): if self._engine() is None or not self._engine()._check_matlab(): raise RejectedExecutionError( pythonengine.getMessage('MatlabTerminated'))
def __validate_engine(self): if self._engine() is None or not self._engine()._check_matlab(): raise RejectedExecutionError(pythonengine.getMessage('MatlabTerminated'))
class MatlabFunc(object): """ Reference to a MATLAB function, where "matlabfunc" is replaced by the function called by the user. *args are passed to MATLAB. **kwargs are only passed to the engine. """ def __init__(self, eng, name): self.__dict__["_engine"] = weakref.ref(eng) self.__dict__["_name"] = name def __getattr__(self, name): return MatlabFunc(self._engine(), "%s.%s" % (self._name, name)) def __setattr__(self, kw, value): raise AttributeError(pythonengine.getMessage('AttrCannotBeAddedToM')) def __call__(self, *args, **kwargs): self.__validate_engine() nargs = kwargs.pop('nargout', 1) if not isinstance(nargs, int): raise TypeError( pythonengine.getMessage('NargoutMustBeInt') + ' %s' % type(nargs).__name__) if nargs < 0: raise ValueError( pythonengine.getMessage('NargoutCannotBeLessThanZero')) async = kwargs.pop('async', False) if not isinstance(async, bool): raise TypeError( pythonengine.getMessage('AsyncMustBeBool') + ' %s' % type(async).__name__) _stdout = kwargs.pop('stdout', None) _stderr = kwargs.pop('stderr', None) if kwargs: raise TypeError( (pythonengine.getMessage('InvalidKwargs') + ' %r') % (list(kwargs.keys())[0])) if (_stdout is not None) and (not isinstance(_stdout, sIO.StringIO)): raise TypeError( (pythonengine.getMessage('StdoutMustBe') + ' %s.%s, ' + pythonengine.getMessage('NOT') + ' %s.%s ') % (sIO.__name__, sIO.StringIO.__name__, _stdout.__class__.__module__, _stdout.__class__.__name__)) if (_stderr is not None) and (not isinstance(_stderr, sIO.StringIO)): raise TypeError( (pythonengine.getMessage('StderrMustBe') + ' %s.%s, ' + pythonengine.getMessage('NOT') + ' %s.%s ') % (sIO.__name__, sIO.StringIO.__name__, _stderr.__class__.__module__, _stderr.__class__.__name__)) future = pythonengine.evaluateFunction(self._engine()._matlab, self._name, nargs, args, out=_stdout, err=_stderr) if async: return FutureResult(self._engine(), future, nargs, _stdout, _stderr, feval=True) else: return FutureResult(self._engine(), future, nargs, _stdout, _stderr, feval=True).result()
def __setattr__(self, kw, value): raise AttributeError(pythonengine.getMessage('AttrCannotBeAddedToM'))
def __setattr__(self, kw, value): raise AttributeError(pythonengine.getMessage('AttrCannotBeAddedToM'))