主要内容

Python 功能的进程外执行

注意

在进程外调用 Python® 函数时存在相关联的开销。此行为影响性能。MathWorks 推荐在进程内调用 Python 函数,这是默认模式。

MATLAB® 可以在单独进程中运行 Python 脚本和函数。在单独进程中运行 Python 使您能够:

  • 在 Python 代码中使用一些与 MATLAB 不兼容的第三方库。

  • 将 MATLAB 进程与 Python 代码中的崩溃隔离。

要在进程外运行,请调用 pyenv 函数并将 "ExecutionMode" 参量设置为 "OutOfProcess"。例如,假设您要在 Python 环境中创建此 list 变量。

['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

要在进程外创建此 list,请将 MATLAB 执行模式设置为 "OutOfProcess"。MATLAB 显示关于您的当前 Python 环境的信息。

pyenv(ExecutionMode="OutOfProcess")
ans = 
  PythonEnvironment with properties:

          Version: "3.11"
       Executable: "C:\Python311\pythonw.exe"
          Library: "C:\windows\system32\python311.dll"
             Home: "C:\Python311"
           Status: NotLoaded
    ExecutionMode: OutOfProcess

创建变量。

py.list({'Monday','Tuesday','Wednesday','Thursday','Friday'})
ans = 

  Python list with no properties.

    ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']

MATLAB 创建一个名为 MATLABPyHost 的进程。

pyenv
ans = 
  PythonEnvironment with properties:

          Version: "3.11"
       Executable: "C:\Python311\pythonw.exe"
          Library: "C:\windows\system32\python311.dll"
             Home: "C:\Python311"
           Status: Loaded
    ExecutionMode: OutOfProcess
        ProcessID: "8196"
      ProcessName: "MATLABPyHost"

注意

清除 Python 对象是异步操作,这意味着,在执行同步调用后,Python 对象可能仍存在于 Python 中。例如,在以下代码中,可能在销毁 myList 之前创建 myList2

myList=py.list;
clear myList
myList2 = py.list;

限制

当您在进程外调用 Python 函数时,在 Python 和 MATLAB 之间传递的变量的大小限制为 2 GB。此限制应用于进程间传递的数据和支持信息。

另请参阅