11"""Wrappers for the interface between ratapi and MATLAB custom files."""
22
3+ import os
34import pathlib
45from contextlib import suppress
56from typing import Callable
@@ -20,10 +21,10 @@ def start_matlab():
2021
2122 """
2223 future = None
23- with suppress ( ImportError ) :
24- import matlab . engine
25-
26- future = matlab .engine .start_matlab (background = True )
24+ if os . environ . get ( "DELAY_MATLAB_START" , '0' ) == '0' :
25+ with suppress ( ImportError ):
26+ import matlab . engine
27+ future = matlab .engine .start_matlab (background = True )
2728
2829 return future
2930
@@ -39,10 +40,11 @@ class MatlabWrapper:
3940 """
4041
4142 loader = start_matlab ()
43+ loader_error_message = "matlabengine is required to use MatlabWrapper"
4244
4345 def __init__ (self , filename : str ) -> None :
4446 if self .loader is None :
45- raise ImportError ("matlabengine is required to use MatlabWrapper" ) from None
47+ raise ImportError (self . loader_error_message ) from None
4648
4749 self .engine = self .loader .result ()
4850 path = pathlib .Path (filename )
@@ -86,6 +88,30 @@ def handle(*args):
8688 return handle
8789
8890
91+ def use_shared_matlab (name , custom_error_message ):
92+ """Connect asynchronously to shared MATLAB engine instance with the given name.
93+
94+ Parameters
95+ ----------
96+ name : str
97+ The name of shared MATLAB engine instance
98+ custom_error_message : str
99+ The custom error message in case of failed connection
100+
101+ Returns
102+ -------
103+ future : matlab.engine.futureresult.FutureResult
104+ A future used to get the actual matlab engine.
105+
106+ """
107+ with suppress (ImportError ):
108+ import matlab .engine
109+
110+ MatlabWrapper .loader = matlab .engine .connect_matlab (name , background = True )
111+ MatlabWrapper .loader_error_message = custom_error_message
112+ return MatlabWrapper .loader
113+
114+
89115class DylibWrapper :
90116 """Creates a python callback for a function in dynamic library.
91117
0 commit comments