Skip to main content
 首页 » 编程设计

python之使用 win32com Dispatch 启动 matlab,应用程序自行关闭

2025年05月04日9itcoder

我正在尝试从 python 启动 matlab,然后执行一个非常基本的测试。

def execute_matlab_command(command): 
    handle = win32com.client.DispatchEx('matlab.application') 
    handle.visible = True 
    # By using print I know that the handle is valid here 
    handle.Execute(command) 
 
execute_matlab_handle("x=32") 

代码运行良好,但 matlab 在调用 handle.Execute(command) 之前关闭。我在这里遗漏了什么,比如 open() 之类的吗?我看到其他人使用(几乎)相同的代码并说它工作正常,我无法解决这个问题。

编辑:Matlab 版本 r2012b,python 版本 2.7

编辑 2:我可能找到了 matlab 关闭的原因。我从 wxPython 中构建的 GUI 调用 DispatchEx,它包含一个主循环。我尝试了一个没有 GUI 的简单脚本,一切正常。如果有人有同样的问题或找到了解决方案,我会在这里留下这个问题。

请您参考如下方法:

质量保证 Calling MATLAB functions from python表示应该没有问题。这Matlab page建议您可能必须配置您的 Matlab 安装以接受以这种方式打开。

注意:作为 COM 服务器对象的“matlab.application”不太可能与您发现的 matlab 包装器有任何关系;包装器只是一个可执行文件。其中一个 matlab 库已注册为 matlab.application 的 COM 服务器。