Matlab Python Engine freezes if a matlab script is running
이전 댓글 표시
Hi, guys, how are you doing?
I'm facing a strange scenery that's driving me crazy...
Due to problems between Numpy and embedded Python interpreter inside a SFunction (everytime I call 'clear mex' and try to reload the SFunction, Matlab crashes due to issues with importing numpy more than once). Considering it's an old problem without solution (there are discussions about it since 2010) I decided to go through another approach and then I decided to implement a solution using the Python API provided by Matlab Python engine.
The first problem I found is:
1) When I call a Python script from Matlab (i.e "py.PY_FILE.PY_METHOD") and this Python script has a 'callback approach' (i.e try to connect to the same Matlab instance shared before), the connection fails.
mlInstances = mlEngine.find_matlab()
if len(mlInstances) == 1:
try:
if self.engineName == '':
future = mlEngine.connect_matlab(mlInstances[0], background=True)
% Connection attempt failed here
self.matlabEngineHandle = future.result()
else:
if self.engineName != mlInstances[0]:
print(Fore.YELLOW + 'Engine name ' + self.engineName + ' is different from Matlab engine found (' + mlInstances[0] + ')')
self.matlabEngineHandle = mlEngine.connect_matlab(mlInstances[0])
except Exception as EngineError:
print(Fore.RED + EngineError)
return False
So, is there any way of calling back and interact with Matlab in this approach?
Looking for an alternative, I built a 'workaround' using an UDP approach. Before calling Matlab script, I run an endless Python script that open an UDP port to wait for a message (that will be send by Matlab script). When Matlab sends this UDP message and Python receives and processes it, the 'callback' approach (interact with Matlab workspace, for example, as shown below) works flawlessly.
import matlab.engine as mlEngine
self.matlabEngineHandle = mlEngine.connect_matlab(mlInstances[0])
def parseMsg(self, msg):
if self.matlabEngineHandle.exist('waitControlVar', 'var'):
self.matlabEngineHandle.workspace['waitControlVar'] = 1
The main problem in this approach is: if I use an endless loop in Matlab to wait to Python script ends (dealing with a condition variable in workspace, for example), Python script will hang if matlabEngine is called.
while true
% Wait until trimming process to finish or time out has been reached
if ~waitControlVar
out = 1;
break;
else
if toc(startTime) > timeLimit
out = 2;
break;
end
end
pause(1);
end
So, is there any way of solving it without using Parallel Computing Toolbox? I tried to understand why I don't have this behavior when using the C++ API (used in SFunction approach).
Thanks in advance, guys!!!
채택된 답변
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Call MATLAB from Python에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!