Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute Python code in a virtualenv from Matlab

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.

like image 824
maximovs Avatar asked Sep 16 '16 18:09

maximovs


People also ask

Can I run a Python program from a MATLAB?

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.

How do I run a Python script in a virtual environment?

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 .

How do I run a Python script in virtual environment Windows?

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).


2 Answers

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')
like image 64
Suever Avatar answered Nov 03 '22 01:11

Suever


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
like image 21
scrutari Avatar answered Nov 03 '22 01:11

scrutari