|
3 | 3 | import os
|
4 | 4 | from pathlib import Path
|
5 | 5 | import sys
|
6 |
| -from tempfile import TemporaryDirectory |
| 6 | +try: |
| 7 | + from tempfile import TemporaryDirectory |
| 8 | +except ImportError: |
| 9 | + from backports import tempfile |
7 | 10 |
|
8 | 11 | from IPython.display import Image
|
9 | 12 | from metakernel import MetaKernel
|
10 | 13 |
|
11 |
| -import matlab.engine |
12 |
| -from matlab.engine import MatlabExecutionError |
13 |
| - |
14 | 14 | from . import __version__
|
15 |
| -from .wurlitzer import Wurlitzer |
| 15 | + |
| 16 | +try: |
| 17 | + from .wurlitzer import Wurlitzer |
| 18 | +except ImportError: |
| 19 | + Wurlitzer = None |
| 20 | + |
| 21 | +try: |
| 22 | + import matlab.engine |
| 23 | + from matlab.engine import MatlabExecutionError |
| 24 | +except ImportError: |
| 25 | + raise ImportError(""" |
| 26 | +Matlab engine not installed: |
| 27 | +See https://www.mathworks.com/help/matlab/matlab-engine-for-python.htm |
| 28 | +""") |
16 | 29 |
|
17 | 30 |
|
18 | 31 | class _PseudoStream:
|
@@ -67,13 +80,10 @@ def do_execute_direct(self, code):
|
67 | 80 | self._matlab.get(0., "defaultfigureposition")[0][2:])
|
68 | 81 | self.handle_plot_settings()
|
69 | 82 |
|
70 |
| - try: |
71 |
| - with Wurlitzer(_PseudoStream(partial(self.Print, end="")), |
72 |
| - _PseudoStream(partial(self.Error, end=""))): |
73 |
| - future = self._matlab.eval(code, nargout=0, async=True) |
74 |
| - future.result() |
75 |
| - except (SyntaxError, MatlabExecutionError, KeyboardInterrupt): |
76 |
| - pass |
| 83 | + if Wurlitzer: |
| 84 | + self._execute_async(code) |
| 85 | + else: |
| 86 | + self._execute_sync(code) |
77 | 87 |
|
78 | 88 | settings = self._validated_plot_settings
|
79 | 89 | if settings["backend"] == "inline":
|
@@ -216,6 +226,27 @@ def do_shutdown(self, restart):
|
216 | 226 | self._matlab.exit()
|
217 | 227 | return super(MatlabKernel, self).do_shutdown(restart)
|
218 | 228 |
|
| 229 | + def _execute_async(self, code): |
| 230 | + try: |
| 231 | + with Wurlitzer(_PseudoStream(partial(self.Print, end="")), |
| 232 | + _PseudoStream(partial(self.Error, end=""))): |
| 233 | + future = self._matlab.eval(code, nargout=0, async=True) |
| 234 | + future.result() |
| 235 | + except (SyntaxError, MatlabExecutionError, KeyboardInterrupt): |
| 236 | + pass |
| 237 | + |
| 238 | + def _execute_sync(self, code): |
| 239 | + out = StringIO() |
| 240 | + err = StringIO() |
| 241 | + try: |
| 242 | + self._matlab.eval(code, nargout=0, stdout=out, stderr=err) |
| 243 | + except (SyntaxError, MatlabExecutionError) as exc: |
| 244 | + stdout = exc.args[0] |
| 245 | + self.Error(stdout) |
| 246 | + return |
| 247 | + stdout = out.getvalue() |
| 248 | + self.Print(stdout) |
| 249 | + |
219 | 250 |
|
220 | 251 | if __name__ == '__main__':
|
221 | 252 | try:
|
|
0 commit comments