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

8 次查看(过去 30 天)
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)

回答(1 个)

Rushikesh
Rushikesh 2024-9-27,11:27
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:

类别

Help CenterFile Exchange 中查找有关 Call Python from MATLAB 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by