From 8cabac1a19b436e9ec3dc0142ec3efb49a48cdd6 Mon Sep 17 00:00:00 2001 From: syntron Date: Wed, 5 Nov 2025 23:57:58 +0100 Subject: [PATCH 1/2] [OMCSessionZMQ] add method to escape strings --- OMPython/ModelicaSystem.py | 2 +- OMPython/OMCSession.py | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index 241b9ffc..e91d3c52 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -2037,7 +2037,7 @@ def prepare(self) -> int: pk_value = pc_structure[idx_structure] if isinstance(pk_value, str): - pk_value_str = pk_value.replace('"', '\\"') + pk_value_str = self.session().escape_str(pk_value) expression = f"setParameterValue({self._model_name}, {pk_structure}, \"{pk_value_str}\")" elif isinstance(pk_value, bool): pk_value_bool_str = "true" if pk_value else "false" diff --git a/OMPython/OMCSession.py b/OMPython/OMCSession.py index fca7c47d..f0c78ef1 100644 --- a/OMPython/OMCSession.py +++ b/OMPython/OMCSession.py @@ -336,7 +336,7 @@ def write_text(self, data: str, encoding=None, errors=None, newline=None): if not isinstance(data, str): raise TypeError(f"data must be str, not {data.__class__.__name__}") - data_omc = data.replace('"', '\\"') + data_omc = self._session.escape_str(data) self._session.sendExpression(f'writeFile("{self.as_posix()}", "{data_omc}", false);') return len(data) @@ -576,6 +576,13 @@ def __del__(self): self.omc_zmq = None + @staticmethod + def escape_str(value: str) -> str: + """ + Escape a string such that it can be used as string within OMC expressions, i.e. escape all double quotes. + """ + return value.replace("\\", "\\\\").replace('"', '\\"') + def omcpath(self, *path) -> OMCPath: """ Create an OMCPath object based on the given path segments and the current OMC session. From cefda6620852bbd808cf3f9ed8f572e62f201a0a Mon Sep 17 00:00:00 2001 From: syntron Date: Thu, 6 Nov 2025 19:44:46 +0100 Subject: [PATCH 2/2] [test_OMCPath] add test_OMCPath_write_file test escape of double quotes and backslash in OMCPath.write_text() / .read_text() --- tests/test_OMCPath.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/test_OMCPath.py b/tests/test_OMCPath.py index b8e937f3..00844905 100644 --- a/tests/test_OMCPath.py +++ b/tests/test_OMCPath.py @@ -76,3 +76,17 @@ def _run_OMCPath_checks(om: OMPython.OMCSessionZMQ): assert p3.parent.is_dir() p3.unlink() assert p3.is_file() is False + + +def test_OMCPath_write_file(tmpdir): + om = OMPython.OMCSessionZMQ() + + data = "abc # \\t # \" # \\n # xyz" + + p1 = om.omcpath_tempdir() + p2 = p1 / 'test.txt' + p2.write_text(data=data) + + assert data == p2.read_text() + + del om