Skip to content

Commit de0bd9b

Browse files
committed
[OMCSession] align definition of sendExpression() - use expr (was: command)
the following classes are not changed - these are obsolete: - OMCSessionZMQ - OMCSessionCmd
1 parent 111d877 commit de0bd9b

2 files changed

Lines changed: 45 additions & 45 deletions

File tree

OMPython/ModelicaSystem.py

Lines changed: 22 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -468,12 +468,12 @@ def set_command_line_options(self, command_line_option: str):
468468
"""
469469
Set the provided command line option via OMC setCommandLineOptions().
470470
"""
471-
exp = f'setCommandLineOptions("{command_line_option}")'
472-
self.sendExpression(exp)
471+
expr = f'setCommandLineOptions("{command_line_option}")'
472+
self.sendExpression(expr=expr)
473473

474474
def _loadFile(self, fileName: OMCPath):
475475
# load file
476-
self.sendExpression(f'loadFile("{fileName.as_posix()}")')
476+
self.sendExpression(expr=f'loadFile("{fileName.as_posix()}")')
477477

478478
# for loading file/package, loading model and building model
479479
def _loadLibrary(self, libraries: list):
@@ -491,7 +491,7 @@ def _loadLibrary(self, libraries: list):
491491
expr_load_lib = f"loadModel({element[0]})"
492492
else:
493493
expr_load_lib = f'loadModel({element[0]}, {{"{element[1]}"}})'
494-
self.sendExpression(expr_load_lib)
494+
self.sendExpression(expr=expr_load_lib)
495495
else:
496496
raise ModelicaSystemError("loadLibrary() failed, Unknown type detected: "
497497
f"{element} is of type {type(element)}, "
@@ -514,8 +514,8 @@ def setWorkDirectory(self, work_directory: Optional[str | os.PathLike] = None) -
514514
raise IOError(f"{workdir} could not be created")
515515

516516
logger.info("Define work dir as %s", workdir)
517-
exp = f'cd("{workdir.as_posix()}")'
518-
self.sendExpression(exp)
517+
expr = f'cd("{workdir.as_posix()}")'
518+
self.sendExpression(expr=expr)
519519

520520
# set the class variable _work_dir ...
521521
self._work_dir = workdir
@@ -561,7 +561,7 @@ def buildModel(self, variableFilter: Optional[str] = None):
561561

562562
def sendExpression(self, expr: str, parsed: bool = True) -> Any:
563563
try:
564-
retval = self._session.sendExpression(command=expr, parsed=parsed)
564+
retval = self._session.sendExpression(expr=expr, parsed=parsed)
565565
except OMCSessionException as ex:
566566
raise ModelicaSystemError(f"Error executing {repr(expr)}: {ex}") from ex
567567

@@ -577,16 +577,16 @@ def _requestApi(
577577
properties: Optional[str] = None,
578578
) -> Any:
579579
if entity is not None and properties is not None:
580-
exp = f'{apiName}({entity}, {properties})'
580+
expr = f'{apiName}({entity}, {properties})'
581581
elif entity is not None and properties is None:
582582
if apiName in ("loadFile", "importFMU"):
583-
exp = f'{apiName}("{entity}")'
583+
expr = f'{apiName}("{entity}")'
584584
else:
585-
exp = f'{apiName}({entity})'
585+
expr = f'{apiName}({entity})'
586586
else:
587-
exp = f'{apiName}()'
587+
expr = f'{apiName}()'
588588

589-
return self.sendExpression(exp)
589+
return self.sendExpression(expr=expr)
590590

591591
def _xmlparse(self, xml_file: OMCPath):
592592
if not xml_file.is_file():
@@ -1275,8 +1275,8 @@ def getSolutions(
12751275
# get absolute path
12761276
result_file = result_file.absolute()
12771277

1278-
result_vars = self.sendExpression(f'readSimulationResultVars("{result_file.as_posix()}")')
1279-
self.sendExpression("closeSimulationResultFile()")
1278+
result_vars = self.sendExpression(expr=f'readSimulationResultVars("{result_file.as_posix()}")')
1279+
self.sendExpression(expr="closeSimulationResultFile()")
12801280
if varList is None:
12811281
return result_vars
12821282

@@ -1293,9 +1293,9 @@ def getSolutions(
12931293
if var not in result_vars:
12941294
raise ModelicaSystemError(f"Requested data {repr(var)} does not exist")
12951295
variables = ",".join(var_list_checked)
1296-
res = self.sendExpression(f'readSimulationResult("{result_file.as_posix()}",{{{variables}}})')
1296+
res = self.sendExpression(expr=f'readSimulationResult("{result_file.as_posix()}",{{{variables}}})')
12971297
np_res = np.array(res)
1298-
self.sendExpression("closeSimulationResultFile()")
1298+
self.sendExpression(expr="closeSimulationResultFile()")
12991299
return np_res
13001300

13011301
@staticmethod
@@ -1395,7 +1395,7 @@ def _set_method_helper(
13951395
"structural, final, protected, evaluated or has a non-constant binding. "
13961396
"Use sendExpression(...) and rebuild the model using buildModel() API; "
13971397
"command to set the parameter before rebuilding the model: "
1398-
"sendExpression(\"setParameterValue("
1398+
"sendExpression(expr=\"setParameterValue("
13991399
f"{self._model_name}, {key}, {val if val is not None else '<?value?>'}"
14001400
")\").")
14011401

@@ -2054,16 +2054,16 @@ def prepare(self) -> int:
20542054
pk_value = pc_structure[idx_structure]
20552055
if isinstance(pk_value, str):
20562056
pk_value_str = self.get_session().escape_str(pk_value)
2057-
expression = f"setParameterValue({self._model_name}, {pk_structure}, \"{pk_value_str}\")"
2057+
expr = f"setParameterValue({self._model_name}, {pk_structure}, \"{pk_value_str}\")"
20582058
elif isinstance(pk_value, bool):
20592059
pk_value_bool_str = "true" if pk_value else "false"
2060-
expression = f"setParameterValue({self._model_name}, {pk_structure}, {pk_value_bool_str});"
2060+
expr = f"setParameterValue({self._model_name}, {pk_structure}, {pk_value_bool_str});"
20612061
else:
2062-
expression = f"setParameterValue({self._model_name}, {pk_structure}, {pk_value})"
2063-
res = self._mod.sendExpression(expression)
2062+
expr = f"setParameterValue({self._model_name}, {pk_structure}, {pk_value})"
2063+
res = self._mod.sendExpression(expr=expr)
20642064
if not res:
20652065
raise ModelicaSystemError(f"Cannot set structural parameter {self._model_name}.{pk_structure} "
2066-
f"to {pk_value} using {repr(expression)}")
2066+
f"to {pk_value} using {repr(expr)}")
20672067

20682068
self._mod.buildModel()
20692069

OMPython/OMCSession.py

Lines changed: 23 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -280,13 +280,13 @@ def is_file(self, *, follow_symlinks=True) -> bool:
280280
"""
281281
Check if the path is a regular file.
282282
"""
283-
return self._session.sendExpression(f'regularFileExists("{self.as_posix()}")')
283+
return self._session.sendExpression(expr=f'regularFileExists("{self.as_posix()}")')
284284

285285
def is_dir(self, *, follow_symlinks=True) -> bool:
286286
"""
287287
Check if the path is a directory.
288288
"""
289-
return self._session.sendExpression(f'directoryExists("{self.as_posix()}")')
289+
return self._session.sendExpression(expr=f'directoryExists("{self.as_posix()}")')
290290

291291
def is_absolute(self):
292292
"""
@@ -304,7 +304,7 @@ def read_text(self, encoding=None, errors=None, newline=None) -> str:
304304
The additional arguments `encoding`, `errors` and `newline` are only defined for compatibility with Path()
305305
definition.
306306
"""
307-
return self._session.sendExpression(f'readFile("{self.as_posix()}")')
307+
return self._session.sendExpression(expr=f'readFile("{self.as_posix()}")')
308308

309309
def write_text(self, data: str, encoding=None, errors=None, newline=None):
310310
"""
@@ -317,7 +317,7 @@ def write_text(self, data: str, encoding=None, errors=None, newline=None):
317317
raise TypeError(f"data must be str, not {data.__class__.__name__}")
318318

319319
data_omc = self._session.escape_str(data)
320-
self._session.sendExpression(f'writeFile("{self.as_posix()}", "{data_omc}", false);')
320+
self._session.sendExpression(expr=f'writeFile("{self.as_posix()}", "{data_omc}", false);')
321321

322322
return len(data)
323323

@@ -330,20 +330,20 @@ def mkdir(self, mode=0o777, parents=False, exist_ok=False):
330330
if self.is_dir() and not exist_ok:
331331
raise FileExistsError(f"Directory {self.as_posix()} already exists!")
332332

333-
return self._session.sendExpression(f'mkdir("{self.as_posix()}")')
333+
return self._session.sendExpression(expr=f'mkdir("{self.as_posix()}")')
334334

335335
def cwd(self):
336336
"""
337337
Returns the current working directory as an OMCPath object.
338338
"""
339-
cwd_str = self._session.sendExpression('cd()')
339+
cwd_str = self._session.sendExpression(expr='cd()')
340340
return OMCPath(cwd_str, session=self._session)
341341

342342
def unlink(self, missing_ok: bool = False) -> None:
343343
"""
344344
Unlink (delete) the file or directory represented by this path.
345345
"""
346-
res = self._session.sendExpression(f'deleteFile("{self.as_posix()}")')
346+
res = self._session.sendExpression(expr=f'deleteFile("{self.as_posix()}")')
347347
if not res and not missing_ok:
348348
raise FileNotFoundError(f"Cannot delete file {self.as_posix()} - it does not exists!")
349349

@@ -373,12 +373,12 @@ def _omc_resolve(self, pathstr: str) -> str:
373373
Internal function to resolve the path of the OMCPath object using OMC functions *WITHOUT* changing the cwd
374374
within OMC.
375375
"""
376-
expression = ('omcpath_cwd := cd(); '
377-
f'omcpath_check := cd("{pathstr}"); ' # check requested pathstring
378-
'cd(omcpath_cwd)')
376+
expr = ('omcpath_cwd := cd(); '
377+
f'omcpath_check := cd("{pathstr}"); ' # check requested pathstring
378+
'cd(omcpath_cwd)')
379379

380380
try:
381-
result = self._session.sendExpression(command=expression, parsed=False)
381+
result = self._session.sendExpression(expr=expr, parsed=False)
382382
result_parts = result.split('\n')
383383
pathstr_resolved = result_parts[1]
384384
pathstr_resolved = pathstr_resolved[1:-1] # remove quotes
@@ -407,7 +407,7 @@ def size(self) -> int:
407407
if not self.is_file():
408408
raise OMCSessionException(f"Path {self.as_posix()} is not a file!")
409409

410-
res = self._session.sendExpression(f'stat("{self.as_posix()}")')
410+
res = self._session.sendExpression(expr=f'stat("{self.as_posix()}")')
411411
if res[0]:
412412
return int(res[1])
413413

@@ -582,7 +582,7 @@ def sendExpression(self, command: str, parsed: bool = True) -> Any:
582582
The complete error handling of the OMC result is done within this method using '"getMessagesStringInternal()'.
583583
Caller should only check for OMCSessionException.
584584
"""
585-
return self.omc_process.sendExpression(command=command, parsed=parsed)
585+
return self.omc_process.sendExpression(expr=command, parsed=parsed)
586586

587587

588588
class PostInitCaller(type):
@@ -701,7 +701,7 @@ def __post_init__(self) -> None:
701701
def __del__(self):
702702
if isinstance(self._omc_zmq, zmq.Socket):
703703
try:
704-
self.sendExpression("quit()")
704+
self.sendExpression(expr="quit()")
705705
except OMCSessionException as exc:
706706
logger.warning(f"Exception on sending 'quit()' to OMC: {exc}! Continue nevertheless ...")
707707
finally:
@@ -759,7 +759,7 @@ def omcpath_tempdir(self, tempdir_base: Optional[OMCPath] = None) -> OMCPath:
759759
if sys.version_info < (3, 12):
760760
tempdir_str = tempfile.gettempdir()
761761
else:
762-
tempdir_str = self.sendExpression("getTempDirectoryPath()")
762+
tempdir_str = self.sendExpression(expr="getTempDirectoryPath()")
763763
tempdir_base = self.omcpath(tempdir_str)
764764

765765
tempdir: Optional[OMCPath] = None
@@ -825,7 +825,7 @@ def execute(self, command: str):
825825

826826
return self.sendExpression(command, parsed=False)
827827

828-
def sendExpression(self, command: str, parsed: bool = True) -> Any:
828+
def sendExpression(self, expr: str, parsed: bool = True) -> Any:
829829
"""
830830
Send an expression to the OMC server and return the result.
831831
@@ -842,12 +842,12 @@ def sendExpression(self, command: str, parsed: bool = True) -> Any:
842842
if self._omc_zmq is None:
843843
raise OMCSessionException("No OMC running. Please create a new instance of OMCSession!")
844844

845-
logger.debug("sendExpression(%r, parsed=%r)", command, parsed)
845+
logger.debug("sendExpression(expr='%r', parsed=%r)", str(expr), parsed)
846846

847847
attempts = 0
848848
while True:
849849
try:
850-
self._omc_zmq.send_string(str(command), flags=zmq.NOBLOCK)
850+
self._omc_zmq.send_string(str(expr), flags=zmq.NOBLOCK)
851851
break
852852
except zmq.error.Again:
853853
pass
@@ -861,7 +861,7 @@ def sendExpression(self, command: str, parsed: bool = True) -> Any:
861861
raise OMCSessionException(f"No connection with OMC (timeout={timeout}). "
862862
f"Log-file says: \n{log_content}")
863863
time.sleep(timeout / 50.0)
864-
if command == "quit()":
864+
if expr == "quit()":
865865
self._omc_zmq.close()
866866
self._omc_zmq = None
867867
return None
@@ -871,13 +871,13 @@ def sendExpression(self, command: str, parsed: bool = True) -> Any:
871871
if result.startswith('Error occurred building AST'):
872872
raise OMCSessionException(f"OMC error: {result}")
873873

874-
if command == "getErrorString()":
874+
if expr == "getErrorString()":
875875
# no error handling if 'getErrorString()' is called
876876
if parsed:
877877
logger.warning("Result of 'getErrorString()' cannot be parsed!")
878878
return result
879879

880-
if command == "getMessagesStringInternal()":
880+
if expr == "getMessagesStringInternal()":
881881
# no error handling if 'getMessagesStringInternal()' is called
882882
if parsed:
883883
logger.warning("Result of 'getMessagesStringInternal()' cannot be parsed!")
@@ -931,7 +931,7 @@ def sendExpression(self, command: str, parsed: bool = True) -> Any:
931931
log_level = log_raw[0][8]
932932
log_id = log_raw[0][9]
933933

934-
msg_short = (f"[OMC log for 'sendExpression({command}, {parsed})']: "
934+
msg_short = (f"[OMC log for 'sendExpression(expr={expr}, parsed={parsed})']: "
935935
f"[{log_kind}:{log_level}:{log_id}] {log_message}")
936936

937937
# response according to the used log level
@@ -953,7 +953,7 @@ def sendExpression(self, command: str, parsed: bool = True) -> Any:
953953
msg_long_list.append(msg_long)
954954
if has_error:
955955
msg_long_str = '\n'.join(f"{idx:02d}: {msg}" for idx, msg in enumerate(msg_long_list))
956-
raise OMCSessionException(f"OMC error occurred for 'sendExpression({command}, {parsed}):\n"
956+
raise OMCSessionException(f"OMC error occurred for 'sendExpression(expr={expr}, parsed={parsed}):\n"
957957
f"{msg_long_str}")
958958

959959
if parsed is False:

0 commit comments

Comments
 (0)