start the python engine via a script

4 visualizaciones (últimos 30 días)
Uwe Brauer
Uwe Brauer el 5 de Jul. de 2018
Respondida: feriel el 3 de Jun. de 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

Respuestas (2)

Siddharth Bhutiya
Siddharth Bhutiya el 11 de Jul. de 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 comentarios
Uwe Brauer
Uwe Brauer el 13 de Jul. de 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 el 20 de Sept. de 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!

Iniciar sesión para comentar.


feriel
feriel el 3 de Jun. de 2023
classfication a un seul couche

Categorías

Más información sobre Call MATLAB from Python en Help Center y File Exchange.

Etiquetas

Productos


Versión

R2016b

Community Treasure Hunt

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

Start Hunting!

Translated by