主要内容

本页翻译不是最新的。点击此处可查看最新英文版本。

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 解释器的默认环境
PythonEnvironmentPython 环境信息
pyrunMATLAB 中运行 Python 语句 (自 R2021b 起)
pyrunfileMATLAB 运行 Python 脚本文件 (自 R2021b 起)
pyargsPython 函数创建关键字参量
matlab.exception.PyException捕获 Python 异常的错误信息

实时编辑器任务

运行 Python 代码在实时编辑器中运行 Python 语句或脚本文件 (自 R2024a 起)

主题

在 MATLAB 中使用 Python 库

从 MATLAB 运行 Python 代码

传递数据

疑难解答

Determine If Error is Python or MATLAB Error

Determine if an error originates in Python or MATLAB code.

无法解析名称 py.myfunc

对加载 Python 失败进行故障排除。

Python 支持的限制

Python 中不支持的 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.

精选示例