Skip to content

Commit b39bdf5

Browse files
syntronadeas31
andauthored
Improve OMCPath (#362)
* [OMCPath] update docstring * [OMCPath] add definition of is_absolute(); consider Windows systems * [OMCPath] improve write_text(); need special handling for double quotes * [OMCPath] update resolve() * [OMCPath] prevent usage of stat() - not implemented using OMC * [OMCPathReal] fix flake8 OMPython/OMCSession.py:339:110: E999 SyntaxError: f-string: unmatched '(' --------- Co-authored-by: Adeel Asghar <[email protected]>
1 parent f986470 commit b39bdf5

File tree

1 file changed

+35
-14
lines changed

1 file changed

+35
-14
lines changed

OMPython/OMCSession.py

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -276,8 +276,11 @@ def getClassNames(self, className=None, recursive=False, qualified=False, sort=F
276276

277277
class OMCPathReal(pathlib.PurePosixPath):
278278
"""
279-
Implementation of a basic Path object which uses OMC as backend. The connection to OMC is provided via a
279+
Implementation of a basic (PurePosix)Path object which uses OMC as backend. The connection to OMC is provided via a
280280
OMCSessionZMQ session object.
281+
282+
PurePosixPath is selected to cover usage of OMC in docker or via WSL. Usage of specialised function could result in
283+
errors as well as usage on a Windows system due to slightly different definitions (PureWindowsPath).
281284
"""
282285

283286
def __init__(self, *path, session: OMCSessionZMQ) -> None:
@@ -304,6 +307,15 @@ def is_dir(self, *, follow_symlinks=True) -> bool:
304307
"""
305308
return self._session.sendExpression(f'directoryExists("{self.as_posix()}")')
306309

310+
def is_absolute(self):
311+
"""
312+
Check if the path is an absolute path considering the possibility that we are running locally on Windows. This
313+
case needs special handling as the definition of is_absolute() differs.
314+
"""
315+
if isinstance(self._session, OMCProcessLocal) and platform.system() == 'Windows':
316+
return pathlib.PureWindowsPath(self.as_posix()).is_absolute()
317+
return super().is_absolute()
318+
307319
def read_text(self, encoding=None, errors=None, newline=None) -> str:
308320
"""
309321
Read the content of the file represented by this path as text.
@@ -321,10 +333,12 @@ def write_text(self, data: str, encoding=None, errors=None, newline=None):
321333
definitions.
322334
"""
323335
if not isinstance(data, str):
324-
raise TypeError('data must be str, not %s' %
325-
data.__class__.__name__)
336+
raise TypeError(f"data must be str, not {data.__class__.__name__}")
337+
338+
data_omc = data.replace('"', '\\"')
339+
self._session.sendExpression(f'writeFile("{self.as_posix()}", "{data_omc}", false);')
326340

327-
return self._session.sendExpression(f'writeFile("{self.as_posix()}", "{data}", false)')
341+
return len(data)
328342

329343
def mkdir(self, mode=0o777, parents=False, exist_ok=False):
330344
"""
@@ -360,15 +374,20 @@ def resolve(self, strict: bool = False):
360374
raise OMCSessionException(f"Path {self.as_posix()} does not exist!")
361375

362376
if self.is_file():
363-
omcpath = self._omc_resolve(self.parent.as_posix()) / self.name
377+
pathstr_resolved = self._omc_resolve(self.parent.as_posix())
378+
omcpath_resolved = self._session.omcpath(pathstr_resolved) / self.name
364379
elif self.is_dir():
365-
omcpath = self._omc_resolve(self.as_posix())
380+
pathstr_resolved = self._omc_resolve(self.as_posix())
381+
omcpath_resolved = self._session.omcpath(pathstr_resolved)
366382
else:
367383
raise OMCSessionException(f"Path {self.as_posix()} is neither a file nor a directory!")
368384

369-
return omcpath
385+
if not omcpath_resolved.is_file() and not omcpath_resolved.is_dir():
386+
raise OMCSessionException(f"OMCPath resolve failed for {self.as_posix()} - path does not exist!")
387+
388+
return omcpath_resolved
370389

371-
def _omc_resolve(self, pathstr: str):
390+
def _omc_resolve(self, pathstr: str) -> str:
372391
"""
373392
Internal function to resolve the path of the OMCPath object using OMC functions *WITHOUT* changing the cwd
374393
within OMC.
@@ -382,15 +401,10 @@ def _omc_resolve(self, pathstr: str):
382401
result_parts = result.split('\n')
383402
pathstr_resolved = result_parts[1]
384403
pathstr_resolved = pathstr_resolved[1:-1] # remove quotes
385-
386-
omcpath_resolved = self._session.omcpath(pathstr_resolved)
387404
except OMCSessionException as ex:
388405
raise OMCSessionException(f"OMCPath resolve failed for {pathstr}!") from ex
389406

390-
if not omcpath_resolved.is_file() and not omcpath_resolved.is_dir():
391-
raise OMCSessionException(f"OMCPath resolve failed for {pathstr} - path does not exist!")
392-
393-
return omcpath_resolved
407+
return pathstr_resolved
394408

395409
def absolute(self):
396410
"""
@@ -418,6 +432,13 @@ def size(self) -> int:
418432

419433
raise OMCSessionException(f"Error reading file size for path {self.as_posix()}!")
420434

435+
def stat(self):
436+
"""
437+
The function stat() cannot be implemented using OMC.
438+
"""
439+
raise NotImplementedError("The function stat() cannot be implemented using OMC; "
440+
"use size() to get the file size.")
441+
421442

422443
if sys.version_info < (3, 12):
423444

0 commit comments

Comments
 (0)