How to create a python 3 class to start MATLAB and keep it running?

Illustration
tamashika - 2025-01-18T23:16:11+00:00
Question: How to create a python 3 class to start MATLAB and keep it running?

I'm using matlab 2017b and python 3 on windows 10. I want to create a class that can start the matlab and keep it open. However, matlab closes right after I finished the python script. Here is the code:   import matlab.engine class Test: def __init__(self): self.eng = matlab.engine.start_matlab("-desktop") if __name__ == "__main__": Test() I can open the matlab in python console with the "start_matlab" command, but with this class I will keep failing to keep it open. Anyone know how I could make this work?

Expert Answer

Profile picture of John Williams John Williams answered . 2025-11-20

test.py

 

import os
class Test:
    def __init__(self):
        self.eng = os.system("matlab -r \"matlab.engine.shareEngine('myMatlabEngine')\"")
if __name__ == "__main__":
    Test()
    

test2.py

import matlab.engine
eng = matlab.engine.connect_matlab('myMatlabEngine')
print(eng.sqrt(4.0))
Usage:
 
Open a terminal
 
python test.py

This keeps MATLAB session running.

Then, open another terminal and call test2.py.

python test2.py

 


Not satisfied with the answer ?? ASK NOW

Get a Free Consultation or a Sample Assignment Review!