Main Content

Call Python from MATLAB

Directly call Python® functionality from MATLAB®

You can access Python libraries directly from MATLAB by adding the py. prefix to the Python name. See Access Python Modules from MATLAB. 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
You can execute Python statements in the Python interpreter directly from MATLAB using the pyrun or pyrunfile functions. For example:
pyrun("l = ['A','new','list']")  % Call list in Python interpreter
For more information, see Directly Call Python Functionality from MATLAB.

If instead you want to call MATLAB functions from Python applications, see Call MATLAB from Python for more information.

Functions

expand all

pyenvChange default environment of Python interpreter
PythonEnvironmentPython environment information
terminateTerminate process associated with Python interpreter
pyrunRun Python statements from MATLAB (Since R2021b)
pyrunfileRun Python script file from MATLAB (Since R2021b)
pyargsCreate keyword arguments for Python function
pystringarrayConvert MATLAB string array to Python NumPy string array (Since R2026a)
matlab.exception.PyExceptionCapture error information for Python exception

Live Editor Tasks

Run Python CodeRun Python statements or script files in the Live Editor (Since R2024a)

Topics

Use Python Environments in MATLAB

Use Python Libraries in MATLAB

Run Python Code from MATLAB

Passing Data

Troubleshooting

Determine If Error is Python or MATLAB Error

Determine if an error originates in Python or MATLAB code.

Unable to resolve the name py.myfunc

Troubleshoot failures loading Python.

Limitations to Python Support

Some Python features are not currently supported in MATLAB.

Handle Python Exceptions

MATLAB catches exceptions thrown by Python and converts them into a matlab.exception.PyException object.

Troubleshooting Matrix and Numeric Argument Errors

Errors might be caused by an input array with more than one dimension whose size is greater than 1.

Error Converting Elements of list or tuple

Use string and numeric converters for list and tuple types.

Featured Examples

Teaching Resources