Skip to content

Commit 59af333

Browse files
committed
Merge branch 'escape_strings' into v4.1.0-syntron3
2 parents fc54d68 + 17571d0 commit 59af333

3 files changed

Lines changed: 23 additions & 2 deletions

File tree

OMPython/ModelicaSystem.py

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

20282028
pk_value = pc_structure[idx_structure]
20292029
if isinstance(pk_value, str):
2030-
pk_value_str = pk_value.replace('"', '\\"')
2030+
pk_value_str = self.session().escape_str(pk_value)
20312031
expression = f"setParameterValue({self._model_name}, {pk_structure}, \"{pk_value_str}\")"
20322032
elif isinstance(pk_value, bool):
20332033
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.

tests/test_OMCPath.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,3 +76,17 @@ def _run_OMCPath_checks(om: OMPython.OMCSessionZMQ):
7676
assert p3.parent.is_dir()
7777
p3.unlink()
7878
assert p3.is_file() is False
79+
80+
81+
def test_OMCPath_write_file(tmpdir):
82+
om = OMPython.OMCSessionZMQ()
83+
84+
data = "abc # \\t # \" # \\n # xyz"
85+
86+
p1 = om.omcpath_tempdir()
87+
p2 = p1 / 'test.txt'
88+
p2.write_text(data=data)
89+
90+
assert data == p2.read_text()
91+
92+
del om

0 commit comments

Comments
 (0)