start the python engine via a script

조회 수: 4 (최근 30일)
Uwe Brauer
Uwe Brauer 2018년 7월 5일
답변: feriel 2023년 6월 3일
I am running Ubuntu 16.04, Matlab 2016b and emacs 27.
I started to use matlab's python engine basically to run matlab code in emacs via juypther and the matlab kernel engine. That works well, but I don't know really enough python to answer the following.
I start the engine via https://es.mathworks.com/help/matlab/matlab_external/start-the-matlab-engine-for-python.html
python3
>> import matlab.engine
>> eng = matlab.engine.start_matlab()
And I stop it via
eng.quit()
Now the question is:
Can't I just write two scripts
startmatlab.py
import matlab.engine
eng = matlab.engine.start_matlab()
And stopmatlab.py
import matlab.engine
eng = matlab.engine.start_matlab()
eng.quit()
And then run
$ python2 startmatlab
I tried but it did not work. What do I miss?
Thanks
Uwe Brauer

답변 (2개)

Siddharth Bhutiya
Siddharth Bhutiya 2018년 7월 11일

The issue here is that when the Python script ends, Python will automatically close the newly created MATLAB Engine. Hence you will not be able to access it.

In order to avoid that you can open a MATLAB instance and type the following command in the MATLAB command window:

>> matlab.engine.shareEngine('my_engine')

This shares the current MATLAB Engine and names it 'my_engine' so that you can connect to it from your jupyter notebook. You can also create a Python script to do this as follows:

import os
os.system('nohup matlab -minimize -r matlab.engine.shareEngine("my_engine")')

Once you have started the MATLAB Engine, you can use it in your code. Here is a simple example on how to do it.

import matlab.engine
eng = matlab.engine.connect_matlab('my_engine')
eng.sqrt(4.0) # You can put your code here

This will return the Python object for the MATLAB Engine named 'my_engine' and assign it to 'eng'. You can then execute whatever MATLAB code you want using the 'eng' Python object.

After you are done you can call 'eng.quit()' or simply close the MATLAB window to stop the MATLAB Engine.

Hope this helps.

  댓글 수: 2
Uwe Brauer
Uwe Brauer 2018년 7월 13일
Hi
thanks very much for this detailed answer. I will look into it and see how easy it is to use.
regards
Uwe
tane martin
tane martin 2020년 9월 20일
Hi Siddarth,
Are there any reasons this code structure would fail? I'm receiving some issues trying exactly this (posted here: https://www.mathworks.com/matlabcentral/answers/595768-python-error-engineerror-unable-to-connect-to-matlab-session#answer_497119)
Thanks!

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


feriel
feriel 2023년 6월 3일
classfication a un seul couche

카테고리

Help CenterFile Exchange에서 Call MATLAB from Python에 대해 자세히 알아보기

태그

제품


릴리스

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by