Usage of "Matlab python engine" from python executed by Matlab

1 view (last 30 days)
To reproduce the error, set up an Matlab + python environment with installed matlab.engine.
Executing the code
py.importlib.import_module('matlab.engine')
gives the following error message:
Error using enginesession>__init__ (line 8)
Python Error: EngineError: MATLAB process session cannot be initialized.
Error in __init__><module> (line 80)
_session = EngineSession()
Error in <frozen importlib>_call_with_frames_removed (line 222)
Error in <frozen importlib>exec_module (line 673)
Error in <frozen importlib>_load_unlocked (line 673)
Error in <frozen importlib>_find_and_load_unlocked (line 958)
Error in <frozen importlib>_find_and_load (line 969)
Error in <frozen importlib>_gcd_import (line 986)
Error in __init__>import_module (line 126)
return _bootstrap._gcd_import(name[level:], package, level)
The basic problem I want to solve by using matlab.engine is to have callbacks from python to Matlab. The trivial solution "passing function handles" is not possible. Is there a different approach possible?
  2 Comments
Tomasz Wyrowinski
Tomasz Wyrowinski on 26 Jul 2017
I've also encountered that problem. Is there any solution or workaround maybe?
Ishaan
Ishaan on 23 Jan 2025
Hey, this issue is not reproducable in MATLAB R2024b with python 3.12. It appears that they fixed it.
Please specify the version if you are still encountering this issue.

Sign in to comment.

Answers (1)

Hitesh
Hitesh on 31 Jan 2025
Hi Patrick,
I too encountered this error in MATLAB R2023b, the workaround that worked for me was to reinstall the "matlabengine" module. Kindly ensure that you need to run following command in this directory "matlabroot\extern\engines\python".
pip install matlabengine
I made a simple simulink model in python. I have saved the model and attached it for your reference.Kindly refer to the below image for the python script.

Community Treasure Hunt

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

Start Hunting!