[How to] Importing python modules in MCC compiled standalone app

6 Ansichten (letzte 30 Tage)
Jiaqi Li
Jiaqi Li am 6 Feb. 2023
Beantwortet: Rushikesh am 27 Sep. 2024
I have a standalone MATLAB app compiled with MCC. Inside this app I need to call python modules that I previously wrote, so the app is built from a function that goes
func(pythonPath, pythonModulePath, etc),
where pythonPath is path to python.exe and pythonModulePath is path to the module that I want to import. In the mcc make function I've also included pythonModulePath via the -a flag and in 'files required for your application to run'.
Inside the code I define pyenv via pythonPath and insert(pythonModulePath), after which I do py.importlib.import('module').
Now, I would like to call py.module.class from 'module'. The ouput of py.importlib.import('module') has listed the class I want to call, so the import was successful there. But when I call py.module.class immediately afterwards, matlab says it is an unrecognized variable or class. Could you please help me? How can I import python modules correctly in matlab MCC compiled apps? (v9.11/2021b)

Antworten (1)

Rushikesh
Rushikesh am 27 Sep. 2024
Hello @Jiaqi Li
I understand that you are trying to initialize class from python imported custom library named ‘module’.
As per MATLAB R2021b, MATLAB does not support accessing class properties using class names and dot operator. Instead, you need to use “py.setattr for initialization or setting parameters. Here is an example of how you can achieve this in MATLAB.
moduleHandle = py.importlib.import_module('module')
classHandle = moduleHandle.MyClass
%To initialize class that takes parameter
py.setattr(classHandle, 'parameter_name', 'value')
%To get function inside class without class name and dot operator
functionHandle = py.getattr(classHandle, 'function_name')
%FunctionHandle(val1, val2, ...) use it as regular function in MATLAB
To know more about python support and py.getattr” and "py.setattr" example, refer to below MATLAB answer:

Kategorien

Mehr zu Call Python from MATLAB finden Sie in Help Center und File Exchange

Produkte


Version

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by