I want to start a shared matlab session then connect to it right away in the same python 3 script. I also want to keep my matlab session opened after the script finishes. Because in the future, I want to write a class to do this, I would like to import all libraries in the header.
The problem is, python 3 script keeps failing to finish if I import os.system
or subprocess.run
first, then use matlab.engine
to connect to matlab. As shown in the code below, my script will be stuck/hanged forever.
# the following code cannot finish running
import os
import matlab.engine
os.system("matlab -r \"matlab.engine.shareEngine\"")
Oddly, if I start matlab using either of os.system
or subprocess.run
without importing matlab.engine
as the answer of my previous question suggested, I can start it without any issue.
I also noticed that if I import matlab.engine
AFTER started matlab (sample code below), the script will finished. Yet this will make my class very ugly...
# the following code can finish running
import os
os.system("matlab -r \"matlab.engine.shareEngine\"")
import matlab.engine
I tried to bypass this issue by using subprocess.Popen
. It did start the matlab and try to use matlab.engine to connect to it without stopping, yet the script can never connect to matlab because matlab.engine will try to connect before matlab finished initializing.
What causes the issue that the script can't finish? How can I import os/subprocess and matlab.engine together in the header? Do I have to make the script stop running for a while in order to wait matlab finished initialization?
For future people:
os.system keeps open until called MATLAB exits. That's why the script can't close itself.