Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion OMPython/ModelicaSystem.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
9 changes: 8 additions & 1 deletion OMPython/OMCSession.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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.
Expand Down
14 changes: 14 additions & 0 deletions tests/test_OMCPath.py
Original file line number Diff line number Diff line change
Expand Up @@ -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