如何在Python循环中运行多个MATLAB脚本?解决会话共享报错
问题描述
希望从Python中运行一个动态变化的MATLAB脚本列表,每次运行的列表可能不同。当前使用的函数如下:
def RunButtonFunc(self): eng = matlab.engine.start_matlab() list_of_matlab_tests = os.listdir(self.matlab_tests_dir) eng.addpath('.\MatlabTests') for key in self.DB: tst_name_without_suffix = self.DB[key][0:len(self.DB[key]) - 2] invert_op = getattr(eng, tst_name_without_suffix, None) if callable(invert_op): invert_op(nargout=0)
当DB中存在重复的MATLAB脚本名时,会触发如下错误:
The current MATLAB session is shared already. To share a session with a different name, launch a new MATLAB session, and then specify the name when you share it.
需要解决该问题,同时想了解是否可以检查会话是否已被共享。
解决方法
复用已有MATLAB会话
不要每次调用RunButtonFunc都重新启动MATLAB引擎,将eng作为类的实例变量在初始化时创建一次,后续直接复用:def __init__(self): # 其他初始化逻辑 self.eng = matlab.engine.start_matlab() self.eng.addpath('.\MatlabTests') # 路径仅需添加一次 def RunButtonFunc(self): list_of_matlab_tests = os.listdir(self.matlab_tests_dir) for key in self.DB: tst_name_without_suffix = self.DB[key][:-2] # 简化字符串切片写法 invert_op = getattr(self.eng, tst_name_without_suffix, None) if callable(invert_op): invert_op(nargout=0)这种方式从根源避免了重复启动会话导致的共享冲突。
检查并连接已有会话
可以通过matlab.engine.find_matlab()获取当前所有运行的MATLAB会话,判断是否存在可用会话,避免重复创建:def get_matlab_engine(self): available_sessions = matlab.engine.find_matlab() if available_sessions: # 连接到第一个可用会话 eng = matlab.engine.connect_matlab(available_sessions[0]) else: # 无可用会话时新建 eng = matlab.engine.start_matlab() eng.addpath('.\MatlabTests') return eng def RunButtonFunc(self): eng = self.get_matlab_engine() list_of_matlab_tests = os.listdir(self.matlab_tests_dir) for key in self.DB: tst_name_without_suffix = self.DB[key][:-2] invert_op = getattr(eng, tst_name_without_suffix, None) if callable(invert_op): invert_op(nargout=0)处理重复脚本名
如果不需要重复执行同一个脚本,先对DB中的脚本名做去重处理:def RunButtonFunc(self): eng = self.get_matlab_engine() # 或复用实例化的self.eng # 提取唯一脚本名 unique_test_names = {self.DB[key][:-2] for key in self.DB} for tst_name in unique_test_names: invert_op = getattr(eng, tst_name, None) if callable(invert_op): invert_op(nargout=0)
内容的提问来源于stack exchange,提问作者evening
相关产品推荐
相关产品推荐

