start the python engine via a script

3 ビュー (過去 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 Center および File ExchangeCall 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