Main Content

MATLAB 中调用 Python

直接从 MATLAB® 调用 Python® 功能

您可以通过将 py. 前缀添加到 Python 名称,直接从 MATLAB 访问 Python 库。请参阅 从 MATLAB 访问 Python 模块 - 快速入门。例如:

py.list({'This','is a','list'})      % Call built-in function list
py.textwrap.wrap('This is a string') % Call wrap function in module textwrap
您可以使用 pyrunpyrunfile 函数直接在 MATLAB 中执行在 Python 解释器中执行的 Python 语句。例如:
pyrun("l = ['A','new','list']")  % Call list in Python interpreter
有关详细信息,请参阅直接从 MATLAB 调用 Python 功能

反过来,如果您想要从 Python 应用程序调用 MATLAB 函数,请参阅从 Python 中调用 MATLAB以获取详细信息。

函数

全部展开

pyenv更改 Python 解释器的默认环境 (自 R2019b 起)
PythonEnvironmentPython 环境信息 (自 R2019b 起)
pyrunMATLAB 中运行 Python 语句 (自 R2021b 起)
pyrunfileMATLAB 运行 Python 脚本文件 (自 R2021b 起)
pyargsPython 函数创建关键字参数
matlab.exception.PyException捕获 Python 异常的错误信息

主题

在 MATLAB 中使用 Python 库

从 MATLAB 运行 Python 代码

传递数据

疑难解答

Determine if Error is Python or MATLAB Error

Tips to determine if an error originates in Python or MATLAB code.

Limitations to Python Support

Python features not 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

Error might be caused by input array with more than one non-singleton dimension.

Error Converting Elements of list or tuple

How to use string and numeric converters for list and tuple types.