python import: dll or dependecies not found from Matlab environment

19 views (last 30 days)
Calling python scripts or functions from matlab has an error at certain import statements, the error is at
py.importlib.import_module('torch')
and equivalents.
Python Error: OSError: [WinError 127] The specified procedure could not be found. Error loading
"C:\Users\jklebes\Miniconda3\envs\myenv\lib\site-packages\torch\lib\shm.dll" or one of its dependencies.
pytorch is installed in the conda environment and can be loaded and run fine in the conda shell in python. The dll exists in the correct location. I don't need to conda or pip reinstall pytorch, because outside of the matlab environment (using python) everything works.
Within matlab, the correct python path is set and other modules in similar locations can be imported, for example
py.importlib.import_module('numpy')
, taking from "C:\Users\jklebes\Miniconda3\envs\myenv\lib\site-packages\numpy", is fine.
I have tried copying everything from system PATH, in an environment where the imports work, using
setenv("PATH", ...)
The PATH in matlab is now the same as in the command prompt, which should in my understanding enable the same DLL to be found by python _frozen_importlib running in an identical environment. Still I get the error that the DLL or its dependencies are not found.
  2 Comments
Binxu Wang
Binxu Wang on 30 Jan 2023
I have the exact same problem as you did, and I tried the exact same method as you did (copying the env variables exactly). I also have no luck.
I'm also querying the official support team to see if there is a known solution....
Thanks for raising this up.
Sivylla Paraskevopoulou
Sivylla Paraskevopoulou on 9 Feb 2023
Maybe setting a Python virtual environment in your working folder will help. For an example on how to set a virtual environmnent and calling PyTorch from MATLAB, see Call Python from MATLAB to Compare PyTorch Models for Image Classification.

Sign in to comment.

Accepted Answer

Nihal Reddy
Nihal Reddy on 15 Feb 2023
I understand you are facing errors at the import statements in your python script while calling it from MATLAB. Issues with MATLAB erroring while importing PyTorch or other libraries are probably caused by a library conflict. Python packages, like PyTorch, often have dependencies on a number of third party libraries with specific version requirements. These may cause issues when MATLAB ships with the same libraries, but with different version requirements. In general, using out-of-process execution mode will avoid these conflicts. For this reason, using out-of-process mode is the best practice when using the Python Interface.
Use the pyenv command to run in out-of-process mode-
>> pyenv("Version","<path to python executable>", "ExecutionMode", "OutOfProcess")

More Answers (0)

Community Treasure Hunt

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

Start Hunting!