MATLAB Answers

Can't both import os.system and matlab.engine at the same time in the header

조회 수: 9(최근 30일)
tamashika
tamashika 10 Jun 2020
댓글: tamashika 18 Jun 2020
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\"")
What causes the issue that the script can't finish? How can I import os/subprocess and matlab.engine together in the header?

  댓글 수: 0

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

채택된 답변

Kojiro Saito
Kojiro Saito 17 Jun 2020
It's because os.system keeps open until called MATLAB exits. That's why I proposed to open another terminal in my Answer.
I guess subprocess is better than os.system in your case.
import os
from subprocess import Popen
Popen("matlab -r \"matlab.engine.shareEngine\"")
The above Python script opens MATLAB engine as a shared, but Python script it self will be closed. So, you can access this shared session from another Python script.
import matlab.engine
names = matlab.engine.find_matlab()
eng = matlab.engine.connect_matlab(names[0]) #names is tuble, so connect to the first one in this example.
print(eng.sqrt(4.0))

  댓글 수: 1

tamashika
tamashika 18 Jun 2020
Ha I didn't know os.system keeps open until called MATLAB exits. Awesome! Thanks

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

추가 답변(0개)

제품


릴리스

R2017b

Community Treasure Hunt

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

Start Hunting!

Translated by