如何在OMPython中设置模型仿真输出文件的存储目录?
解决OMPython中ModelicaSystem指定仿真输出目录的问题
使用OMPython的ModelicaSystem对象运行模型时,仿真输出文件默认会存到用户目录,无法方便地批量清理。想要自定义这些文件的存储目录(推测为工作目录),但两次尝试均未解决问题:
第一次尝试(未生效)
直接修改ModelicaSystem的currDir属性无法生效:
from OMPython import OMCSessionZMQ omc = OMCSessionZMQ() model_path=omc.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels/" simulation_path=omc.sendExpression("getTempDirectoryPath()")+"OMtmp/" from OMPython import ModelicaSystem mod=ModelicaSystem(model_path+"BouncingBall.mo","BouncingBall") mod.currDir=simulation_path mod.simulate()
第二次尝试(无法删除临时目录)
通过os.chdir()切换Python工作目录后,OMC会话未同步目录变化,且仿真文件被进程占用无法删除:
import os import errno import shutil from OMPython import OMCSessionZMQ from OMPython import ModelicaSystem omc = OMCSessionZMQ() # Create temporary directory simulation_path=omc.sendExpression("getTempDirectoryPath()")+"OMtmp/" home_path=os.getcwd() try: os.mkdir(simulation_path) except OSError as e: if e.errno != errno.EEXIST: raise os.chdir(simulation_path) print("Working directory->"+os.getcwd()) # Loading the model and simulating model_path=omc.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels/" mod=ModelicaSystem(model_path+"BouncingBall.mo","BouncingBall") mod.simulate() res=mod.getSolutions(["time","h"]) print("The heigth is "+str(res[1,-1])+" m") #Changing the working directory to the original one os.chdir(home_path) # We could delete files and dierctory using: shutil.rmtree(simulation_path) # But don't work. Plan b, delete al de files in the directory for files in os.listdir(simulation_path): path = os.path.join(simulation_path, files) try: shutil.rmtree(path) except OSError: os.remove(path) # Still don't work: os.rmdir(simulation_path)
正确解决方案
要指定仿真输出目录,需通过OMC会话的cd()命令切换工作目录,同时确保仿真完成后释放文件锁:
import os import shutil from OMPython import OMCSessionZMQ, ModelicaSystem # 创建OMC会话 omc = OMCSessionZMQ() # 设置路径 model_path = omc.sendExpression("getInstallationDirectoryPath()") + "/share/doc/omc/testmodels/" simulation_path = omc.sendExpression("getTempDirectoryPath()") + "OMtmp/" # 确保仿真目录存在 os.makedirs(simulation_path, exist_ok=True) # 让OMC会话切换到目标目录 omc.sendExpression(f'cd("{simulation_path}")') # 加载模型并仿真 mod = ModelicaSystem(model_path + "BouncingBall.mo", "BouncingBall") mod.simulate() # 获取结果 res = mod.getSolutions(["time", "h"]) print(f"The height is {res[1,-1]} m") # 关闭OMC会话,释放文件锁 omc.sendExpression("quit()") # 删除仿真目录及所有文件 shutil.rmtree(simulation_path)
关键要点
- 必须通过
omc.sendExpression(f'cd("{simulation_path}")')让OMC内核切换工作目录,才能让仿真输出文件生成在指定路径 - 仿真完成后调用
omc.sendExpression("quit()")关闭OMC会话,避免文件被进程占用无法删除 - 使用
os.makedirs(..., exist_ok=True)简化目录创建逻辑,无需手动处理已存在的情况
内容的提问来源于stack exchange,提问作者Alberto
相关产品推荐
相关产品推荐

