diff --git a/OMPython/ModelicaSystem.py b/OMPython/ModelicaSystem.py index d0c504c5..0985961c 100644 --- a/OMPython/ModelicaSystem.py +++ b/OMPython/ModelicaSystem.py @@ -2054,7 +2054,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. 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