Main Content

直接从 MATLAB 调用 Python 功能

您可以从 Python® 库中调用功能,或直接从 MATLAB® 中执行 Python 语句。

访问 Python 模块

要访问 Python 库,请在 Python 名称前添加 py. 前缀。例如:

py.list({'This','is a','list'})      % Call built-in function list
py.textwrap.wrap('This is a string') % Call wrap function in module textwrap

有关详细信息,请参阅从 MATLAB 访问 Python 模块 - 快速入门

运行 Python 代码

要在 MATLAB 命令提示符下执行 Python 解释器中的 Python 语句,请使用 pyrun 函数。使用此函数,您可以运行将 MATLAB 类型作为输入传递的代码,并将一些或所有变量返回到 MATLAB。例如,假设您在 Python 解释器中运行这条语句。

>>> l = ['A', 'new', 'list']

要从 MATLAB 运行该语句,请使用 pyrun。要将结果返回到 MATLAB 变量 myList,请添加 "l" 作为 outputs 参量:

myList = pyrun("l = ['A', 'new', 'list']", "l");

运行 Python 脚本

要从 MATLAB 命令提示符调用 Python 脚本,请使用 pyrunfile 函数。您传递 MATLAB 数据并返回变量的方式与 pyrun 相同。例如,用以下语句创建一个 mklist.py 文件:

# Python script file mklist.py: 
s = 'list'
L = ['A', 'new', s]

从 MATLAB 运行脚本:

myListFile = pyrunfile("mklist.py", "L")
myListFile = 
  Python list with no properties.

    ['A', 'new', 'list']

访问 Python 变量

当您使用 py. 前缀时,MATLAB 会导入整个模块,并且可以访问 Python 代码的所有函数和类。但是,当您使用 pyrunpyrunfile 函数执行 Python 代码时,如果您要访问 Python 数据,则必须使用 outvars 参量将 Python 对象显式返回到 MATLAB。

pyrunpyrunfile 函数的限制

如果将类的实例返回到 MATLAB,则无法修改使用 pyrunpyrunfile 定义的 Python 类。如果需要更改类定义,请重新启动解释器会话:

terminate(pyenv)
pyenv(ExecutionMode="OutOfProcess")

或者,重新启动 MATLAB 以使用 "InProcess" 模式。

有些局部变量要由其他局部变量通过某种方法来初始化,pyrunpyrunfile 函数不支持具有这种局部变量的类。对于这种用法,创建一个模块并使用 py. 前缀访问它。

另请参阅

|

相关主题

外部网站