Skip to content

Commit 83552d8

Browse files
syntronadeas31
andauthored
[OMCSessionZMQ] escape strings to be used via OMC (#369)
* [OMCSessionZMQ] add method to escape strings * [test_OMCPath] add test_OMCPath_write_file test escape of double quotes and backslash in OMCPath.write_text() / .read_text() --------- Co-authored-by: Adeel Asghar <adeel.asghar@liu.se>
1 parent 444e051 commit 83552d8

File tree

3 files changed

+23
-2
lines changed

3 files changed

+23
-2
lines changed

OMPython/ModelicaSystem.py

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

20552055
pk_value = pc_structure[idx_structure]
20562056
if isinstance(pk_value, str):
2057-
pk_value_str = pk_value.replace('"', '\\"')
2057+
pk_value_str = self.session().escape_str(pk_value)
20582058
expression = f"setParameterValue({self._model_name}, {pk_structure}, \"{pk_value_str}\")"
20592059
elif isinstance(pk_value, bool):
20602060
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)