Skip to content

Commit 3dfc0de

Browse files
committed
[ModelicaSystem._run_cmd] merge all calls to executeable into one function
* merge all calls to executeables into one function - _run_cmd() * simplify & cleanup the code
1 parent 7fd956a commit 3dfc0de

File tree

1 file changed

+55
-50
lines changed

1 file changed

+55
-50
lines changed

OMPython/__init__.py

Lines changed: 55 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -928,6 +928,55 @@ def setTempDirectory(self, customBuildDirectory):
928928
def getWorkDirectory(self):
929929
return self.tempdir
930930

931+
def _run_cmd(self, cmd: list, verbose: bool = True):
932+
logger.debug("Run OM command {} in {}".format(cmd, self.tempdir))
933+
934+
if platform.system() == "Windows":
935+
omhome = os.path.join(os.environ.get("OPENMODELICAHOME"))
936+
dllPath = (os.path.join(omhome, "bin")
937+
+ os.pathsep + os.path.join(omhome, "lib/omc")
938+
+ os.pathsep + os.path.join(omhome, "lib/omc/cpp")
939+
+ os.pathsep + os.path.join(omhome, "lib/omc/omsicpp"))
940+
941+
# include path to resources of defined external libraries
942+
for element in self.lmodel:
943+
if element is not None:
944+
if isinstance(element, str):
945+
if element.endswith("package.mo"):
946+
pkgpath = element[:-10] + '/Resources/Library/'
947+
for wver in ['win32', 'win64']:
948+
pkgpath_wver = pkgpath + '/' + wver
949+
if os.path.exists(pkgpath_wver):
950+
dllPath = pkgpath_wver + os.pathsep + dllPath
951+
952+
# fix backslash in path definitions
953+
dllPath = dllPath.replace("\\", "/")
954+
955+
my_env = os.environ.copy()
956+
my_env["PATH"] = dllPath + os.pathsep + my_env["PATH"]
957+
else:
958+
# TODO: how to handle path to resources of external libraries for any system not Windows?
959+
my_env = None
960+
961+
currentDir = os.getcwd()
962+
try:
963+
os.chdir(self.tempdir)
964+
p = subprocess.Popen(cmd, env=my_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
965+
stdout, stderr = p.communicate()
966+
967+
stdout = stdout.decode('ascii').strip()
968+
stderr = stderr.decode('ascii').strip()
969+
if stderr:
970+
logger.warning("OM error: {}".format(stderr))
971+
if verbose and stdout:
972+
logger.info("OM output:\n{}".format(stdout))
973+
p.wait()
974+
p.terminate()
975+
os.chdir(currentDir)
976+
except Exception as e:
977+
os.chdir(currentDir)
978+
raise Exception("Error running command {}: {}".format(repr(cmd), e))
979+
931980
def buildModel(self, variableFilter=None, verbose=True):
932981
if variableFilter is not None:
933982
self.variableFilter = variableFilter
@@ -1280,44 +1329,15 @@ def simulate(self, resultfile=None, simflags=None, verbose=True): # 11
12801329
getExeFile = os.path.join(self.tempdir, '{}.{}'.format(self.modelName, "exe")).replace("\\", "/")
12811330
else:
12821331
getExeFile = os.path.join(self.tempdir, self.modelName).replace("\\", "/")
1283-
currentDir = os.getcwd()
1284-
if (os.path.exists(getExeFile)):
1332+
1333+
if os.path.exists(getExeFile):
12851334
cmd = getExeFile + override + csvinput + r + simflags
12861335
cmd = cmd.split(" ")
1287-
#print(cmd)
1288-
os.chdir(self.tempdir)
1289-
if (platform.system() == "Windows"):
1290-
omhome = os.path.join(os.environ.get("OPENMODELICAHOME"))
1291-
dllPath = os.path.join(omhome, "bin").replace("\\", "/") + os.pathsep + \
1292-
os.path.join(omhome, "lib/omc").replace("\\", "/") + os.pathsep + \
1293-
os.path.join(omhome, "lib/omc/cpp").replace("\\", "/") + os.pathsep + \
1294-
os.path.join(omhome, "lib/omc/omsicpp").replace("\\", "/")
1295-
for element in self.lmodel:
1296-
if element is not None:
1297-
if isinstance(element, str):
1298-
if element.endswith("package.mo"):
1299-
pkgpath = element[:-10] + '/Resources/Library/'
1300-
for wver in ['win32', 'win64']:
1301-
pkgpath_wver = pkgpath + '/' + wver
1302-
if os.path.exists(pkgpath_wver):
1303-
dllPath = pkgpath_wver + os.pathsep + dllPath
1304-
my_env = os.environ.copy()
1305-
my_env["PATH"] = dllPath + os.pathsep + my_env["PATH"]
1306-
else:
1307-
my_env = None
1336+
self._run_cmd(cmd=cmd, verbose=verbose)
13081337

1309-
p = subprocess.Popen(cmd, env=my_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1310-
stdout, stderr = p.communicate()
1311-
if stderr:
1312-
logger.warning(f"OM error: {stderr.decode('ascii')}")
1313-
if verbose and stdout:
1314-
logger.info(f"OM output:\n{stdout.decode('ascii').strip()}")
1315-
p.wait()
1316-
p.terminate()
1317-
os.chdir(currentDir)
13181338
self.simulationFlag = True
13191339
else:
1320-
raise Exception("Error: Application file path not found: " + getExeFile)
1340+
raise Exception("Error: Application file path not found: " + getExeFile)
13211341

13221342
# to extract simulation results
13231343
def getSolutions(self, varList=None, resultfile=None): # 12
@@ -1753,23 +1773,11 @@ def linearize(self, lintime = None, simflags= None): # 22
17531773
if simflags is None:
17541774
simflags = ""
17551775

1756-
currentDir = os.getcwd()
17571776
if (os.path.exists(getExeFile)):
17581777
cmd = getExeFile + linruntime + override + csvinput + simflags
1759-
# print(cmd)
1760-
os.chdir(self.tempdir)
1761-
if (platform.system() == "Windows"):
1762-
omhome = os.path.join(os.environ.get("OPENMODELICAHOME"))
1763-
dllPath = os.path.join(omhome, "bin").replace("\\", "/") + os.pathsep + os.path.join(omhome, "lib/omc").replace("\\", "/") + os.pathsep + os.path.join(omhome, "lib/omc/cpp").replace("\\", "/") + os.pathsep + os.path.join(omhome, "lib/omc/omsicpp").replace("\\", "/")
1764-
my_env = os.environ.copy()
1765-
my_env["PATH"] = dllPath + os.pathsep + my_env["PATH"]
1766-
p = subprocess.Popen(cmd, env=my_env)
1767-
p.wait()
1768-
p.terminate()
1769-
else:
1770-
os.system(cmd)
1778+
cmd = cmd.split(' ')
1779+
self._run_cmd(cmd=cmd)
17711780
else:
1772-
os.chdir(currentDir)
17731781
raise Exception("Error: Application file path not found: " + getExeFile)
17741782

17751783
# code to get the matrix and linear inputs, outputs and states
@@ -1792,13 +1800,10 @@ def linearize(self, lintime = None, simflags= None): # 22
17921800
self.linearoutputs = outputVars
17931801
self.linearstates = stateVars
17941802
return [A, B, C, D]
1795-
os.chdir(currentDir)
17961803
except:
1797-
os.chdir(currentDir)
17981804
raise Exception("ModuleNotFoundError: No module named 'linearized_model'")
17991805
else:
18001806
errormsg = self.getconn.sendExpression("getErrorString()")
1801-
os.chdir(currentDir)
18021807
return print("Linearization failed: ", "\"" , linearFile,"\"" ," not found \n", errormsg)
18031808

18041809

0 commit comments

Comments
 (0)