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?
Thanks

 採用された回答

Kojiro Saito
Kojiro Saito 2020 年 6 月 2 日

0 投票

How about using matlab.engine.shareEngine?
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

4 件のコメント

tamashika
tamashika 2020 年 6 月 2 日
Thanks for the solution, but I think your test.py will do the trick by itself. Even after I closed the console which ran test.py, matlab would still stay open. Is there something I miss?
tamashika
tamashika 2020 年 6 月 2 日
Hey Kojiro, I think I know what I missed. If we use matlab engine to start matlab, matlab will close when the script close since the variable will be cleared. You are proposing to use os.system to open a shared session of matlab, and connect to that matlab using matlab engine everytime I want to do the calculation. I think that's brilliant. I can't think of any other better way. Thanks again for the help!
Kojiro Saito
Kojiro Saito 2020 年 6 月 2 日
Hi Andy, yes, as document explains, "If you exit Python with an engine still running, then Python automatically stops the engine and its MATLAB process.", so matlab.engine.start_matlab cannot keep MATLAB engine running if the Python is exited. That's why I've recommended to use matlab.engine.shareEngine. But Python's matlab.engine does not have shareEngine, so I proposed to use os.system command instead.
tamashika
tamashika 2020 年 6 月 16 日

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

製品

リリース

R2017b

質問済み:

2020 年 6 月 1 日

コメント済み:

2020 年 6 月 16 日

Community Treasure Hunt

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

Start Hunting!

Translated by