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
13 changes: 10 additions & 3 deletions OMPython/OMCSession.py
Original file line number Diff line number Diff line change
Expand Up @@ -282,12 +282,19 @@ def omcpath_tempdir(self, tempdir_base: Optional[OMPathABC] = None) -> OMPathABC
def execute(self, command: str):
return self.omc_process.execute(command=command)

def sendExpression(self, command: str, parsed: bool = True, raise_on_error: bool = True) -> Any:
def sendExpression(
self,
command: str,
parsed: bool = True,
raise_on_error: bool = True,
) -> Any: # pylint: disable=W0237
"""
Send an expression to the OMC server and return the result.

The complete error handling of the OMC result is done within this method using '"getMessagesStringInternal()'.
Caller should only check for OMSessionException.
The complete error handling of the OMC result is done within this method using 'getMessagesStringInternal()'.
Caller should only check for OMCSessionException.

Compatibility: 'command' was renamed to 'expr'
"""
return self.omc_process.sendExpression(expr=command, parsed=parsed, raise_on_error=raise_on_error)

Expand Down
2 changes: 1 addition & 1 deletion OMPython/modelica_system_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -1026,7 +1026,7 @@ def setInputs(
self._inputs[key] = [(float(self._simulate_options["startTime"]), float(val)),
(float(self._simulate_options["stopTime"]), float(val))]
elif isinstance(val_evaluated, list):
if not all([isinstance(item, tuple) for item in val_evaluated]):
if not all(isinstance(item, tuple) for item in val_evaluated):
raise ModelicaSystemError("Value for setInput() must be in tuple format; "
f"got {repr(val_evaluated)}")
if val_evaluated != sorted(val_evaluated, key=lambda x: x[0]):
Expand Down
12 changes: 6 additions & 6 deletions OMPython/om_session_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,13 @@ def with_segments(self, *pathsegments) -> OMPathABC:
return type(self)(*pathsegments, session=self._session)

@abc.abstractmethod
def is_file(self) -> bool:
def is_file(self, *, follow_symlinks=True) -> bool:
"""
Check if the path is a regular file.
"""

@abc.abstractmethod
def is_dir(self) -> bool:
def is_dir(self, *, follow_symlinks: bool = True) -> bool:
"""
Check if the path is a directory.
"""
Expand All @@ -115,19 +115,19 @@ def is_absolute(self) -> bool:
"""

@abc.abstractmethod
def read_text(self) -> str:
def read_text(self, encoding=None, errors=None, newline=None) -> str:
"""
Read the content of the file represented by this path as text.
"""

@abc.abstractmethod
def write_text(self, data: str) -> int:
def write_text(self, data: str, encoding=None, errors=None, newline=None) -> int:
"""
Write text data to the file represented by this path.
"""

@abc.abstractmethod
def mkdir(self, parents: bool = True, exist_ok: bool = False) -> None:
def mkdir(self, mode=0o777, parents: bool = False, exist_ok: bool = False) -> None:
"""
Create a directory at the path represented by this class.

Expand All @@ -137,7 +137,7 @@ def mkdir(self, parents: bool = True, exist_ok: bool = False) -> None:
"""

@abc.abstractmethod
def cwd(self) -> OMPathABC:
def cwd(self) -> OMPathABC: # pylint: disable=W0221 # is @classmethod in the original; see pathlib.PathBase
"""
Returns the current working directory as an OMPathABC object.
"""
Expand Down
22 changes: 16 additions & 6 deletions OMPython/om_session_omc.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,19 +52,23 @@ class _OMCPath(OMPathABC):
OMCSession* classes.
"""

def is_file(self) -> bool:
def is_file(self, *, follow_symlinks=True) -> bool:
"""
Check if the path is a regular file.
"""
del follow_symlinks

retval = self.get_session().sendExpression(expr=f'regularFileExists("{self.as_posix()}")')
if not isinstance(retval, bool):
raise OMSessionException(f"Invalid return value for is_file(): {retval} - expect bool")
return retval

def is_dir(self) -> bool:
def is_dir(self, *, follow_symlinks: bool = True) -> bool:
"""
Check if the path is a directory.
"""
del follow_symlinks

retval = self.get_session().sendExpression(expr=f'directoryExists("{self.as_posix()}")')
if not isinstance(retval, bool):
raise OMSessionException(f"Invalid return value for is_dir(): {retval} - expect bool")
Expand All @@ -78,19 +82,23 @@ def is_absolute(self) -> bool:
return pathlib.PureWindowsPath(self.as_posix()).is_absolute()
return pathlib.PurePosixPath(self.as_posix()).is_absolute()

def read_text(self) -> str:
def read_text(self, encoding=None, errors=None, newline=None) -> str:
"""
Read the content of the file represented by this path as text.
"""
del encoding, errors, newline

retval = self.get_session().sendExpression(expr=f'readFile("{self.as_posix()}")')
if not isinstance(retval, str):
raise OMSessionException(f"Invalid return value for read_text(): {retval} - expect str")
return retval

def write_text(self, data: str) -> int:
def write_text(self, data: str, encoding=None, errors=None, newline=None) -> int:
"""
Write text data to the file represented by this path.
"""
del encoding, errors, newline

if not isinstance(data, str):
raise TypeError(f"data must be str, not {data.__class__.__name__}")

Expand All @@ -99,21 +107,23 @@ def write_text(self, data: str) -> int:

return len(data)

def mkdir(self, parents: bool = True, exist_ok: bool = False) -> None:
def mkdir(self, mode=0o777, parents: bool = False, exist_ok: bool = False) -> None:
"""
Create a directory at the path represented by this class.

The argument parents with default value True exists to ensure compatibility with the fallback solution for
Python < 3.12. In this case, pathlib.Path is used directly and this option ensures, that missing parent
directories are also created.
"""
del mode

if self.is_dir() and not exist_ok:
raise FileExistsError(f"Directory {self.as_posix()} already exists!")

if not self._session.sendExpression(expr=f'mkdir("{self.as_posix()}")'):
raise OMSessionException(f"Error on directory creation for {self.as_posix()}!")

def cwd(self) -> OMPathABC:
def cwd(self) -> OMPathABC: # pylint: disable=W0221 # is @classmethod in the original; see pathlib.PathBase
"""
Returns the current working directory as an OMPathABC object.
"""
Expand Down
41 changes: 29 additions & 12 deletions OMPython/om_session_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,16 +49,20 @@ class _OMPathRunnerLocal(OMPathRunnerABC):
conversion via pathlib.Path(<OM*Path*>.as_posix()).
"""

def is_file(self) -> bool:
def is_file(self, *, follow_symlinks=True) -> bool:
"""
Check if the path is a regular file.
"""
del follow_symlinks

return self._path().is_file()

def is_dir(self) -> bool:
def is_dir(self, *, follow_symlinks: bool = True) -> bool:
"""
Check if the path is a directory.
"""
del follow_symlinks

return self._path().is_dir()

def is_absolute(self) -> bool:
Expand All @@ -67,32 +71,38 @@ def is_absolute(self) -> bool:
"""
return self._path().is_absolute()

def read_text(self) -> str:
def read_text(self, encoding=None, errors=None, newline=None) -> str:
"""
Read the content of the file represented by this path as text.
"""
del encoding, errors, newline

return self._path().read_text(encoding='utf-8')

def write_text(self, data: str):
def write_text(self, data: str, encoding=None, errors=None, newline=None):
"""
Write text data to the file represented by this path.
"""
del encoding, errors, newline

if not isinstance(data, str):
raise TypeError(f"data must be str, not {data.__class__.__name__}")

return self._path().write_text(data=data, encoding='utf-8')

def mkdir(self, parents: bool = True, exist_ok: bool = False) -> None:
def mkdir(self, mode=0o777, parents: bool = False, exist_ok: bool = False) -> None:
"""
Create a directory at the path represented by this class.

The argument parents with default value True exists to ensure compatibility with the fallback solution for
Python < 3.12. In this case, pathlib.Path is used directly and this option ensures, that missing parent
directories are also created.
"""
del mode

self._path().mkdir(parents=parents, exist_ok=exist_ok)

def cwd(self) -> OMPathABC:
def cwd(self) -> OMPathABC: # pylint: disable=W0221 # is @classmethod in the original; see pathlib.PathBase
"""
Returns the current working directory as an OMPathABC object.
"""
Expand Down Expand Up @@ -132,10 +142,12 @@ class _OMPathRunnerBash(OMPathRunnerABC):
conversion via pathlib.Path(<OM*Path*>.as_posix()).
"""

def is_file(self) -> bool:
def is_file(self, *, follow_symlinks=True) -> bool:
"""
Check if the path is a regular file.
"""
del follow_symlinks

cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'test -f "{self.as_posix()}"']

Expand All @@ -145,7 +157,7 @@ def is_file(self) -> bool:
except subprocess.CalledProcessError:
return False

def is_dir(self) -> bool:
def is_dir(self, *, follow_symlinks: bool = True) -> bool:
"""
Check if the path is a directory.
"""
Expand All @@ -172,10 +184,12 @@ def is_absolute(self) -> bool:
except subprocess.CalledProcessError:
return False

def read_text(self) -> str:
def read_text(self, encoding=None, errors=None, newline=None) -> str:
"""
Read the content of the file represented by this path as text.
"""
del encoding, errors, newline

cmdl = self.get_session().get_cmd_prefix()
cmdl += ['bash', '-c', f'cat "{self.as_posix()}"']

Expand All @@ -184,10 +198,12 @@ def read_text(self) -> str:
return result.stdout.decode('utf-8')
raise FileNotFoundError(f"Cannot read file: {self.as_posix()}")

def write_text(self, data: str) -> int:
def write_text(self, data: str, encoding=None, errors=None, newline=None) -> int:
"""
Write text data to the file represented by this path.
"""
del encoding, errors, newline

if not isinstance(data, str):
raise TypeError(f"data must be str, not {data.__class__.__name__}")

Expand All @@ -202,14 +218,15 @@ def write_text(self, data: str) -> int:
except subprocess.CalledProcessError as exc:
raise IOError(f"Error writing data to file {self.as_posix()}!") from exc

def mkdir(self, parents: bool = True, exist_ok: bool = False) -> None:
def mkdir(self, mode=0o777, parents: bool = False, exist_ok: bool = False) -> None:
"""
Create a directory at the path represented by this class.

The argument parents with default value True exists to ensure compatibility with the fallback solution for
Python < 3.12. In this case, pathlib.Path is used directly and this option ensures, that missing parent
directories are also created.
"""
del mode

if self.is_file():
raise OSError(f"The given path {self.as_posix()} exists and is a file!")
Expand All @@ -226,7 +243,7 @@ def mkdir(self, parents: bool = True, exist_ok: bool = False) -> None:
except subprocess.CalledProcessError as exc:
raise OMSessionException(f"Error on directory creation for {self.as_posix()}!") from exc

def cwd(self) -> OMPathABC:
def cwd(self) -> OMPathABC: # pylint: disable=W0221 # is @classmethod in the original; see pathlib.PathBase
"""
Returns the current working directory as an OMPathABC object.
"""
Expand Down
Loading