Skip to content

Commit 5d1c38d

Browse files
committed
[OMCSession] align definition of sendExpression() - use expr (was: command)
the following classes are not changed - tehse are obsolete: - OMCSessionZMQ - OMCSessionCmd
1 parent 76b73e5 commit 5d1c38d

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
@@ -466,12 +466,12 @@ def set_command_line_options(self, command_line_option: str):
466466
"""
467467
Set the provided command line option via OMC setCommandLineOptions().
468468
"""
469-
exp = f'setCommandLineOptions("{command_line_option}")'
470-
self.sendExpression(exp)
469+
expr = f'setCommandLineOptions("{command_line_option}")'
470+
self.sendExpression(expr=expr)
471471

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

476476
# for loading file/package, loading model and building model
477477
def _loadLibrary(self, libraries: list):
@@ -489,7 +489,7 @@ def _loadLibrary(self, libraries: list):
489489
expr_load_lib = f"loadModel({element[0]})"
490490
else:
491491
expr_load_lib = f'loadModel({element[0]}, {{"{element[1]}"}})'
492-
self.sendExpression(expr_load_lib)
492+
self.sendExpression(expr=expr_load_lib)
493493
else:
494494
raise ModelicaSystemError("loadLibrary() failed, Unknown type detected: "
495495
f"{element} is of type {type(element)}, "
@@ -512,8 +512,8 @@ def setWorkDirectory(self, work_directory: Optional[str | os.PathLike] = None) -
512512
raise IOError(f"{workdir} could not be created")
513513

514514
logger.info("Define work dir as %s", workdir)
515-
exp = f'cd("{workdir.as_posix()}")'
516-
self.sendExpression(exp)
515+
expr = f'cd("{workdir.as_posix()}")'
516+
self.sendExpression(expr=expr)
517517

518518
# set the class variable _work_dir ...
519519
self._work_dir = workdir
@@ -559,7 +559,7 @@ def buildModel(self, variableFilter: Optional[str] = None):
559559

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

@@ -575,16 +575,16 @@ def _requestApi(
575575
properties: Optional[str] = None,
576576
) -> Any:
577577
if entity is not None and properties is not None:
578-
exp = f'{apiName}({entity}, {properties})'
578+
expr = f'{apiName}({entity}, {properties})'
579579
elif entity is not None and properties is None:
580580
if apiName in ("loadFile", "importFMU"):
581-
exp = f'{apiName}("{entity}")'
581+
expr = f'{apiName}("{entity}")'
582582
else:
583-
exp = f'{apiName}({entity})'
583+
expr = f'{apiName}({entity})'
584584
else:
585-
exp = f'{apiName}()'
585+
expr = f'{apiName}()'
586586

587-
return self.sendExpression(exp)
587+
return self.sendExpression(expr=expr)
588588

589589
def _xmlparse(self, xml_file: OMCPath):
590590
if not xml_file.is_file():
@@ -1258,8 +1258,8 @@ def getSolutions(
12581258
# get absolute path
12591259
result_file = result_file.absolute()
12601260

1261-
result_vars = self.sendExpression(f'readSimulationResultVars("{result_file.as_posix()}")')
1262-
self.sendExpression("closeSimulationResultFile()")
1261+
result_vars = self.sendExpression(expr=f'readSimulationResultVars("{result_file.as_posix()}")')
1262+
self.sendExpression(expr="closeSimulationResultFile()")
12631263
if varList is None:
12641264
return result_vars
12651265

@@ -1276,9 +1276,9 @@ def getSolutions(
12761276
if var not in result_vars:
12771277
raise ModelicaSystemError(f"Requested data {repr(var)} does not exist")
12781278
variables = ",".join(var_list_checked)
1279-
res = self.sendExpression(f'readSimulationResult("{result_file.as_posix()}",{{{variables}}})')
1279+
res = self.sendExpression(expr=f'readSimulationResult("{result_file.as_posix()}",{{{variables}}})')
12801280
np_res = np.array(res)
1281-
self.sendExpression("closeSimulationResultFile()")
1281+
self.sendExpression(expr="closeSimulationResultFile()")
12821282
return np_res
12831283

12841284
@staticmethod
@@ -1378,7 +1378,7 @@ def _set_method_helper(
13781378
"structural, final, protected, evaluated or has a non-constant binding. "
13791379
"Use sendExpression(...) and rebuild the model using buildModel() API; "
13801380
"command to set the parameter before rebuilding the model: "
1381-
"sendExpression(\"setParameterValue("
1381+
"sendExpression(expr=\"setParameterValue("
13821382
f"{self._model_name}, {key}, {val if val is not None else '<?value?>'}"
13831383
")\").")
13841384

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

20652065
self._mod.buildModel()
20662066

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:
706706
pass
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
@@ -823,7 +823,7 @@ def execute(self, command: str):
823823

824824
return self.sendExpression(command, parsed=False)
825825

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

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

845845
attempts = 0
846846
while True:
847847
try:
848-
self._omc_zmq.send_string(str(command), flags=zmq.NOBLOCK)
848+
self._omc_zmq.send_string(str(expr), flags=zmq.NOBLOCK)
849849
break
850850
except zmq.error.Again:
851851
pass
@@ -859,7 +859,7 @@ def sendExpression(self, command: str, parsed: bool = True) -> Any:
859859
raise OMCSessionException(f"No connection with OMC (timeout={timeout}). "
860860
f"Log-file says: \n{log_content}")
861861
time.sleep(timeout / 50.0)
862-
if command == "quit()":
862+
if expr == "quit()":
863863
self._omc_zmq.close()
864864
self._omc_zmq = None
865865
return None
@@ -869,13 +869,13 @@ def sendExpression(self, command: str, parsed: bool = True) -> Any:
869869
if result.startswith('Error occurred building AST'):
870870
raise OMCSessionException(f"OMC error: {result}")
871871

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

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

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

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

957957
if parsed is False:

0 commit comments

Comments
 (0)