[How to] Importing python modules in MCC compiled standalone app
4 次查看(过去 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)
0 个评论
回答(1 个)
Rushikesh
2024-9-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:
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Call Python from MATLAB 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!