Calling Python 3rd party packages from Matlab

4 vues (au cours des 30 derniers jours)
Jonathan King
Jonathan King le 26 Fév 2021
Is it possible to use 3rd party python packages/subpackages from within Matlab? (as opposed to 3rd party modules)
I have a package ("mypackage") for python2.7. I installed it in a conda environment (using conda 4.9.2) and have verified I can run its modules from a Python console. The package has two subpackages: "modelA" and "modelB". Each subpackage holds a module named "run" that holds various commands for the relevant model.
I would like to be able call the two different "run" modules from within a Matlab script (Matlab 2020b). The ideal would be something like:
py.mypackage.modelA.run.foo(inputs)
and
py.mypackage.modelB.run.bar(different_inputs)
I've added "mypackage" to both the Python and Matlab search paths, and have tried moving the working directory to the folder holding "mypackage", but I always get the error: "Unable to resolve the name py.mypackage.modelA.run.foo".
I have been able to run a module successfully by moving the working directory to "...\mypackage\modelA", and then calling
py.run.foo(inputs)
However, if I then try moving to "...mypackage\modelB" and calling
py.run.bar(different_inputs)
I get another "Unable to resolve the name" error. My best guess is that the Python search path is still pointing to the "run" module for modelA, as I am still able to call py.run.foo. If this is the case, is it possible to remove a module from the Python search path in order to toggle between modules?

Réponses (1)

Varun Sai Alaparthi
Varun Sai Alaparthi le 16 Nov 2022
Hello Jonathan,
I understand that you are facing issue with calling modules in 3rd party python packages from MATLAB.
Yes, it is possible to use 3 rd party python packages from MATLAB.
Try executing these commands in the MATLAB command window before executing your code.
% Terminate the existing python environment.
terminate(pyenv)
% Set the Execution Mode to OutOfProcess.
pe = pyenv('ExecutionMode','OutOfProcess');
py.importlib.import_module('mypackage');
This should solve the error : Unable to resolve the name py.mypackage.modelA.run.foo”.
Please feel free to reach out in case the error persists.
Sincerely
Varun

Catégories

En savoir plus sur Python Package Integration dans Help Center et File Exchange

Produits


Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by