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

14 次查看(过去 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