Directly Call Python Functionality from MATLAB
You can call functionality from Python® libraries or execute Python statements directly from MATLAB®.
Access Python Modules
To access Python libraries, add the py.
prefix to the
Python name. For example:
py.list({'This','is a','list'}) % Call built-in function list py.textwrap.wrap('This is a string') % Call wrap function in module textwrap
For more information, see Access Python Modules from MATLAB - Getting Started.
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. For example, suppose that you run this statement in a Python interpreter.
>>> l = ['A', 'new', 'list']
To run the statement from MATLAB, use pyrun
. To
return the result to a MATLAB variable myList
, add "l"
as an
outputs
argument:
myList = pyrun("l = ['A', 'new', 'list']", "l");
Run Python Scripts
To call a Python script from the MATLAB command prompt, use the pyrunfile
function. You pass MATLAB data and return variables the same way as with pyrun
. For
example, create a mklist.py
file with these statements:
# Python script file mklist.py:
s = 'list'
L = ['A', 'new', s]
Run the script from MATLAB:
myListFile = pyrunfile("mklist.py", "L")
myListFile = Python list with no properties. ['A', 'new', 'list']
Access to Python Variables
When you use the py.
prefix, MATLAB imports the entire module and can access all functions and classes of the
Python code. However, when you execute Python code using the pyrun
or pyrunfile
functions, if you want to access Python data you must explicitly return Python objects to MATLAB using the outvars
argument.
Limitations to pyrun
and pyrunfile
Functions
Python classes defined using pyrun
or pyrunfile
cannot be modified if you return an instance of the class to MATLAB. If you need to change class definitions, restart the interpreter session:
terminate(pyenv) pyenv(ExecutionMode="OutOfProcess")
Alternatively, restart MATLAB for "InProcess"
.
The pyrun
and pyrunfile
functions do not support classes with local variables that are initialized by other local variables through methods. For such usage, create a module and access it using the py.
prefix.