I am creating a Matlab toolbox for research and I need to execute Matlab code but also Python code.
I want to allow the user to execute Python code from Matlab. The problem is that if I do it right away, I would have to install everything on the Python's environment and I want to avoid this using virtualenv. The problem is that I don't know how to tell Matlab to user the virtual enviornment created.
Run Python Code To execute Python statements in the Python interpreter from the MATLAB command prompt, use the pyrun function. With this function, you can run code that passes MATLAB types as input and returns some or all of the variables back to MATLAB.
To use the virtual environment you created to run Python scripts, simply invoke Python from the command line in the context where you activated it. For instance, to run a script, just run python myscript.py .
In "Program/script" textbox you set the path to Python executable (in my case is inside the virtualenv folder). "Add arguments" => Just the name of your Python script (name. ppy). "Start in" => The full path of your Python script (without the name.py).
You can either modify the PATH
environment variable in MATLAB prior to calling python from MATLAB
% Modify the system PATH so it finds the python executable in your venv first
setenv('PATH', ['/path/to/my/venv/bin', pathsep, getenv('PATH')])
% Call your python script
system('python myscript.py')
Or the better way would be to specify the full path to the python binary
system('/path/to/my/venv/bin/python myscript.py')
As suggested in comment by @tales-pádua you may use pyversion command to set path to Python executable you are using (before trying to call python from Matlab).
This can be automated by use of matlabrc.m file:
python = '.local/bin/python';
if exist(python, 'file')
pyversion(python)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With