Calling matlab.eng​ine.connec​t_matlab() twice freezes Python

I can connect to a named running MATLAB session from Python with:
In [8]: matlab.engine.connect_matlab('MY_SESSION')
But if I call it a second time Python hangs for about a minute before finally saying it can not connect
In [8]: matlab.engine.connect_matlab('MY_SESSION')
Out[8]: <matlab.engine.matlabengine.MatlabEngine at 0x1648f46a370>
In [9]: matlab.engine.connect_matlab('MY_SESSION')
...
EngineError: Unable to connect to MATLAB session 'MY_SESSION'.
I can not find a way of testing if MY_SESSION already exists. I also can not find a way to close a connection that already exists in a different scope. Are those things possible?

답변 (1개)

Chris
Chris 2023년 1월 29일
편집: Chris 2023년 1월 29일
names = matlab.engine.find_matlab()
if 'MY_SESSION' in names:
eng = matlab.engine.connect_matlab('MY_SESSION')
You can del(eng) to close the connection in the present scope, but I'm not sure about forcing it closed from somewhere else.
Since Matlab takes a bit to do its thing, connecting/reconnecting will sometimes throw an error. You might use a try/except or a while loop to handle the error in a python script/program.

댓글 수: 5

I don't think that if statement helps. I am connecting to a MATLAB session that already exists and is named. I am pretty sure that matlab.engine.find_matlab() will return the name of the session regardless of whether or not I have connected to it.
@Rob Campbell If you name the connection (eng here) in the python shell and delete it when you're done, I don't think it should do anything funky in between? And I can connect to the shared session simultaneously from multiple shells. So maybe I'm not understanding the issue.
If I try to connect to it twice from the same shell it locks the terminal for a minute the second time then issues an arror. I didn't try different shells. Because I have this issue I was looking for a way to tell if a connection is under way.
Chris
Chris 2023년 1월 30일
편집: Chris 2023년 1월 30일
Then if the variable is present, the connection is there. Make a function that tests that condition before connecting.
We are getting side tracked now.
I want a way to test whether the connection has been made and it looks like that does not exist.
Thanks for trying, though.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Call MATLAB from Python에 대해 자세히 알아보기

제품

릴리스

R2022b

질문:

2023년 1월 28일

댓글:

2023년 1월 30일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by