How does one get MATLAB to load Python libraries and scripts?

64 visualizaciones (últimos 30 días)
Vincent Hall
Vincent Hall el 14 de Oct. de 2019
Respondida: QUAN WANG el 14 de Nov. de 2022
I'm working on MATLAB 2018a, so cannot use pyenv, so I've been using pyversion.
OS: Windows 10 Pro, version 1809, 64 bit.
I can get MATLAB to call simple Python code, as long as it has no library calls:
If the Python code is called tryRunInMATLAB.py, and it is:
# -*- coding: utf-8 -*-
def printThis():
Lisa = list([9,18,27])
print("Lisa is " + str(Lisa) )
return
Then trying to call it in MATLAB 2018a:
folder = "ThisHereFolder"
file = "tryRunInMATLAB.py"
% Add to MATLAB path:
addpath(folder)
% Add to Python path:
P = py.sys.path;
if count(P,folder) == 0
insert(P,int32(0),folder);
end
py.tryRunInMATLAB.printThis()
Undefined variable "py" or class "py.tryRunInMATLAB.printThis".
Oh, maybe it does't even work for that now.
Maybe this'll help?
py.importlib.import_module("Drive:\\path\\PythonTest\tryRunInMATLAB.py")
Nope:
Error using <frozen importlib>_find_and_load_unlocked (line 965)
Python Error: ModuleNotFoundError: No module named 'Drive:\\path\\PythonTest\\tryRunInMATLAB'
Error in <frozen importlib>_find_and_load (line 983)
Error in <frozen importlib>_gcd_import (line 1006)
Error in <frozen importlib>_call_with_frames_removed (line 219)
Error in <frozen importlib>_find_and_load_unlocked (line 953)
Error in <frozen importlib>_find_and_load (line 983)
Error in <frozen importlib>_gcd_import (line 1006)
Error in __init__>import_module (line 127)
return _bootstrap._gcd_import(name[level:], package, level)
Also tried these:
py.importlib.import_module(file)
Error using <frozen importlib>_find_and_load_unlocked (line 962)
Python Error: ModuleNotFoundError: No module named 'tryRunInMATLAB.py'; 'tryRunInMATLAB' is not a package
Error in <frozen importlib>_find_and_load (line 983)
Error in <frozen importlib>_gcd_import (line 1006)
Error in __init__>import_module (line 127)
return _bootstrap._gcd_import(name[level:], package, level)
py.importlib.reload(file)
Error using __init__>reload (line 140)
Python Error: TypeError: reload() argument must be a module
Same answer
Anyway, I've also tried to add libraries by:
anacond = "Drive:\path\Continuum\anaconda3\"
if count(P,anacond) == 0
insert(P,int32(0),anacond)
end
% And even:
if count(P,"Drive:\path\Continuum\anaconda3\Lib\site-packages\")==0 % This is where the libraries for Python are.
insert(P,int32(0),"Drive:\path\Continuum\anaconda3\Lib\site-packages\")
end
plt = py.matplotlib.plot([9,8,7,6,4])
Undefined variable "py" or class "py.matplotlib.plot".
Obviously, I'm not giving my true paths here.
What about just importing a library?
>> py.importlib.import_module('matplotlib')
Error using _distributor_init><module> (line 34)
Python Error: ImportError: DLL load failed: The specified module could not be found.
Error in __init__><module> (line 140)
from . import _distributor_init
Error in __init__><module> (line 33)
import numpy as np
Error in __init__><module> (line 141)
from . import cbook, rcsetup
Error in <frozen importlib>_call_with_frames_removed (line 219)
Error in <frozen importlib>exec_module (line 728)
Error in <frozen importlib>_load_unlocked (line 677)
Error in <frozen importlib>_find_and_load_unlocked (line 967)
Error in <frozen importlib>_find_and_load (line 983)
Error in <frozen importlib>_gcd_import (line 1006)
Error in __init__>import_module (line 127)
return _bootstrap._gcd_import(name[level:], package, level)
What about?
py.importlib.import_module('matplotlib\pyplot.py')
No luck anywhere.
Am I doing something stupid or obviously missing something?
Thanks.
  2 comentarios
Rafael Rebouças
Rafael Rebouças el 19 de En. de 2021
Editada: Rafael Rebouças el 19 de En. de 2021
You did everything right!
I tried all theses codes and I couldn't import a library from another directory.
My solution:
% Simple way to load your library
copyfile(my_library_file_path, pwd, 'f');
% It's necessary to load library
py.my_library.any_method_or_function();
delete 'my_library.py';
Now, your Python library is loaded to use in any directory.
Jin
Jin el 27 de Mzo. de 2021
Hi Rafael,
I tried your way not working, can you kindly help?
function MatlabCallPy
sArchPath = 'D:\Program Files\Python37\Lib\site-packages\arch\unitroot';
copyfile(sArchPath, pwd, 'f');
testvalue = randn(100,2);
py.arch.unitroot.KPSS(testvalue);
end
Undefined variable "py" or class "py.arch.unitroot.KPSS".

Iniciar sesión para comentar.

Respuestas (4)

Jozsef Orban
Jozsef Orban el 7 de Ag. de 2020
I was struggling for a day with the same error. I see that you had all things done, so I just have some questions instead of answer.
What does pyversion state? Which bit version of python you have? It should match with Matlab bit version (64 in your case).
My case:
pyversion
version: '3.6'
executable: 'C:\Data\Python36\python.exe'
library: 'C:\Data\Python36\python36.dll'
home: 'C:\Data\Python36'
isloaded: 1
My mistake was that I left this in the code as originally intended to call Matlab from python, but now I switched to the inverse direction.
import matlab.engine
This is not a module (or at least it is not accepted in this case), so it killed the loed process.
Now this seems to be the right case, if Matlab answers something similar:
py.importlib.import_module('yoursciptfilename')
ans =
Python module with properties:
sys: [1×1 py.module]
TopasDevice: [1×1 py.CLR.CLR Metatype]
Topas4SDKExample: [1×1 py.type]
main: [1×1 py.function]
msvcrt: [1×1 py.module]
Mint: [1×1 py.CLR.ModuleObject]
time: [1×1 py.module]
clr: [1×1 py.module]
Do you have several python versions? It may mislead the Matlab.
Last, but most important, if your code runs in python, it may not run in Matlab python engine... as I come to realise now. (5 min ago). So check for all errors and wrong function definitions!
I hope it helps!

Rafael Rebouças
Rafael Rebouças el 19 de En. de 2021
Editada: Rafael Rebouças el 19 de En. de 2021
My solution:
% Simple way to load your library
copyfile(my_library_file_path, pwd, 'f');
% It's necessary to load library
py.my_library.any_method_or_function();
delete 'my_library.py';
Now, your Python library is loaded to use in any directory.

Jin
Jin el 27 de Mzo. de 2021
Editada: Jin el 27 de Mzo. de 2021
Getting the same issue as I am migrating my old Matlab app written in 2017 to a Win10 recently. M code calls ARCH toolbox in Python which are all typical functions, and they works well on Two Win 7 machines.
I install Matlab2017 and Python packages on Win10 exactly the same way what I did to the two Win7 machines. However, code on Win10 it just does not work. All paths and site package are correctly installed.
>> py.sys.path
ans =
Python list with no properties.
['', 'D:\\Program Files\\Python37\\python37.zip', 'D:\\Program Files\\Python37\\DLLs', 'D:\\Program Files\\Python37\\lib', 'D:\\Program Files\\Python37', 'D:\\Program Files\\Python37\\lib\\site-packages']
After comparing pyversion output, I found the 'isloaded' is TRUE on Win10, while this value is FALSE on the other two Win7 machines. Explanation of this output is blurred on Matlab website, when it is True does it is meaning Matlab already pre-loaded core py packages so it is not going to load libs?
Would setting the value as ‘FALSE’ help? Is there a way to do this?
version: '3.7'
executable: 'D:\Program Files\Python37\python.EXE'
library: 'D:\Program Files\Python37\python37.dll'
home: 'D:\Program Files\Python37'
isloaded: 1
version: '3.7'
executable: 'E:\Python37\python.EXE'
library: 'E:\Python37\python37.dll'
home: 'E:\Python37'
isloaded: 0
version: '3.6'
executable: 'C:\Users\Rupesi\AppData\Local\Programs\Python\Python36\python.EXE'
library: 'C:\Users\Rupesi\AppData\Local\Programs\Python\Python36\python36.dll'
home: 'C:\Users\Rupesi\AppData\Local\Programs\Python\Python36'
isloaded: 0
  2 comentarios
Jin
Jin el 27 de Mzo. de 2021
Run Matlab using Admin on Win10 and found the isloaded value now is 0 but still
Undefined variable "py" or class "py.arch.unitroot.standardfunction".
Jin
Jin el 27 de Mzo. de 2021
Problem solved, it turns out to be dependency between Python 3.6 and Cython having issues.

Iniciar sesión para comentar.


QUAN WANG
QUAN WANG el 14 de Nov. de 2022
Hello, I am struggling with the same error, any help?
% clc;clear;
if count(py.sys.path,'')==0
insert(py.sys.path,int32(0),'');
end
mod=py.importlib.import_module('Demo01');
py.importlib.reload(mod);
ANS=mod.HJX(1,2);
disp("output:");disp(ANS);
error tips:
错误使用 <frozen importlib>_find_and_load_unlocked (第 984 行)
Python 错误 ModuleNotFoundError: No module named 'Demo01'
出错 <frozen importlib>_find_and_load (第 1007 行)
出错 <frozen importlib>_gcd_import (第 1030 行)
出错 __init__>import_module (第 127 行)
thanks

Categorías

Más información sobre Call Python from MATLAB en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by