class MatlabEngine(object): def __init__(self): if 'OCTAVE_EXECUTABLE' in os.environ: self._engine = Octave(os.environ['OCTAVE_EXECUTABLE']) self._engine.start() self.name = 'octave' elif matlab_native: self._engine = matlab.engine.start_matlab() self.name = 'matlab' else: executable = os.environ.get('MATLAB_EXECUTABLE', 'matlab') self._engine = Matlab(executable) self._engine.start() self.name = 'pymatbridge' # add MATLAB-side helper functions to MATLAB's path if self.name != 'octave': kernel_path = os.path.dirname(os.path.realpath(__file__)) toolbox_path = os.path.join(kernel_path, 'toolbox') self.run_code("addpath('%s');" % toolbox_path) def run_code(self, code): if matlab_native: return self._run_native(code) return self._engine.run_code(code) def stop(self): if matlab_native: self._engine.exit() else: self._engine.stop() def _run_native(self, code): resp = dict(success=True, content=dict()) out = StringIO() err = StringIO() if sys.version_info[0] < 3: code = str(code) try: self._engine.eval(code, nargout=0, stdout=out, stderr=err) self._engine.eval(''' figures = {}; handles = get(0, 'children'); for hi = 1:length(handles) datadir = fullfile(tempdir(), 'MatlabData'); if ~exist(datadir, 'dir'); mkdir(datadir); end figures{hi} = [fullfile(datadir, ['MatlabFig', sprintf('%03d', hi)]), '.png']; saveas(handles(hi), figures{hi}); if (strcmp(get(handles(hi), 'visible'), 'off')); close(handles(hi)); end end''', nargout=0, stdout=out, stderr=err) figures = self._engine.workspace['figures'] except (SyntaxError, MatlabExecutionError) as exc: resp['content']['stdout'] = exc.args[0] resp['success'] = False else: resp['content']['stdout'] = out.getvalue() if figures: resp['content']['figures'] = figures return resp
class MatlabEngine(object): def __init__(self): if 'OCTAVE_EXECUTABLE' in os.environ: self._engine = Octave(os.environ['OCTAVE_EXECUTABLE']) self._engine.start() self.name = 'octave' elif matlab_native: self._engine = matlab.engine.start_matlab() self.name = 'matlab' else: executable = os.environ.get('MATLAB_EXECUTABLE', 'matlab') self._engine = Matlab(executable) self._engine.start() self.name = 'pymatbridge' # add MATLAB-side helper functions to MATLAB's path if self.name != 'octave': kernel_path = os.path.dirname(os.path.realpath(__file__)) toolbox_path = os.path.join(kernel_path, 'toolbox') self.run_code("addpath('%s');" % toolbox_path) def run_code(self, code): if matlab_native: return self._run_native(code) return self._engine.run_code(code) def stop(self): if matlab_native: self._engine.exit() else: self._engine.stop() def _run_native(self, code): out = StringIO() err = StringIO() if sys.version_info[0] < 3: code = str(code) try: self._engine.eval(code, nargout=0, stdout=out, stderr=err) except (SyntaxError, MatlabExecutionError) as exc: return dict(success=False, content=dict(stdout=exc.args[0])) return dict(success=True, content=dict(stdout=out.getvalue()))