Python importer only works when the .py file is in the working directory

조회 수: 11 (최근 30일)
I use the python importer to use python scripts to create a simulink library, but these library blocks only work when the .py file is in the working directory of Matlab. For organisational reasons, I don't want to store all the python files in a single directory. I already tried to use 'addpath(genpath('folder'))', which does not seem to work. Also when importing the file with the directory added (py.importlib.import_module('Drive/folder/file');) I also have no success. In another forum post from 2021 I saw a suggestion to make a temporary copy of the python file, but I feel like that would severely influence the computational efficiency of the simulation. Is there a way in which I can work with multiple python files in different folders?

채택된 답변

Caspar
Caspar 2024년 1월 4일
Hi Bastiaan,
One workaround is to add the path of the directory that contains the Python file with the function you need, using the Python sys module.
For example, in the setupImpl function before the module gets imported:
function setupImpl(obj)
pyrun("import sys");
pyrun("sys.path.append('directory')");
py.importlib.import_module('simple_function');
end
Greetings,
Caspar

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Call Python from MATLAB에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by