Skip to content

Commit aab8a1f

Browse files
committed
[OMCSessionZMQ] add method to escape strings
1 parent 42c4f87 commit aab8a1f

File tree

2 files changed

+9
-2
lines changed

2 files changed

+9
-2
lines changed

OMPython/ModelicaSystem.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1977,7 +1977,7 @@ def prepare(self) -> int:
19771977

19781978
pk_value = pc_structure[idx_structure]
19791979
if isinstance(pk_value, str):
1980-
pk_value_str = pk_value.replace('"', '\\"')
1980+
pk_value_str = self.session().escape_str(pk_value)
19811981
expression = f"setParameterValue({self._model_name}, {pk_structure}, \"{pk_value_str}\")"
19821982
elif isinstance(pk_value, bool):
19831983
pk_value_bool_str = "true" if pk_value else "false"

OMPython/OMCSession.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ def write_text(self, data: str, encoding=None, errors=None, newline=None):
336336
if not isinstance(data, str):
337337
raise TypeError(f"data must be str, not {data.__class__.__name__}")
338338

339-
data_omc = data.replace('"', '\\"')
339+
data_omc = self._session.escape_str(data)
340340
self._session.sendExpression(f'writeFile("{self.as_posix()}", "{data_omc}", false);')
341341

342342
return len(data)
@@ -576,6 +576,13 @@ def __del__(self):
576576

577577
self.omc_zmq = None
578578

579+
@staticmethod
580+
def escape_str(value: str) -> str:
581+
"""
582+
Escape a string such that it can be used as string within OMC expressions, i.e. escape all double quotes.
583+
"""
584+
return value.replace("\\", "\\\\").replace('"', '\\"')
585+
579586
def omcpath(self, *path) -> OMCPath:
580587
"""
581588
Create an OMCPath object based on the given path segments and the current OMC session.

0 commit comments

Comments
 (0)