start the python engine via a script

1 view (last 30 days)
Uwe Brauer
Uwe Brauer on 5 Jul 2018
Answered: feriel on 3 Jun 2023
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

Answers (2)

Siddharth Bhutiya
Siddharth Bhutiya on 11 Jul 2018

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 Comments
Uwe Brauer
Uwe Brauer on 13 Jul 2018
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 on 20 Sep 2020
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!

Sign in to comment.


feriel
feriel on 3 Jun 2023
classfication a un seul couche

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!