| 225 | |
| 226 | |
| 227 | class SysCommand: |
| 228 | def __init__( |
| 229 | self, |
| 230 | cmd: str | list[str], |
| 231 | peek_output: bool | None = False, |
| 232 | environment_vars: dict[str, str] | None = None, |
| 233 | working_directory: str = './', |
| 234 | remove_vt100_escape_codes_from_lines: bool = True, |
| 235 | ): |
| 236 | self.cmd = cmd |
| 237 | self.peek_output = peek_output |
| 238 | self.environment_vars = environment_vars |
| 239 | self.working_directory = working_directory |
| 240 | self.remove_vt100_escape_codes_from_lines = remove_vt100_escape_codes_from_lines |
| 241 | |
| 242 | self.session: SysCommandWorker | None = None |
| 243 | self.create_session() |
| 244 | |
| 245 | def __enter__(self) -> SysCommandWorker | None: |
| 246 | return self.session |
| 247 | |
| 248 | def __exit__(self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) -> None: |
| 249 | # b''.join(sys_command('sync')) # No need to, since the underlying fs() object will call sync. |
| 250 | # TODO: https://stackoverflow.com/questions/28157929/how-to-safely-handle-an-exception-inside-a-context-manager |
| 251 | |
| 252 | if exc_type is not None: |
| 253 | error(str(exc_value)) |
| 254 | |
| 255 | def __iter__(self, *args: list[Any], **kwargs: dict[str, Any]) -> Iterator[bytes]: |
| 256 | if self.session: |
| 257 | yield from self.session |
| 258 | |
| 259 | def __getitem__(self, key: slice) -> bytes: |
| 260 | if not self.session: |
| 261 | raise KeyError('SysCommand() does not have an active session.') |
| 262 | elif type(key) is slice: |
| 263 | start = key.start or 0 |
| 264 | end = key.stop or len(self.session._trace_log) |
| 265 | |
| 266 | return self.session._trace_log[start:end] |
| 267 | else: |
| 268 | raise ValueError("SysCommand() doesn't have key & value pairs, only slices, SysCommand('ls')[:10] as an example.") |
| 269 | |
| 270 | @override |
| 271 | def __repr__(self, *args: list[Any], **kwargs: dict[str, Any]) -> str: |
| 272 | return self.decode('UTF-8', errors='backslashreplace') or '' |
| 273 | |
| 274 | def create_session(self) -> bool: |
| 275 | """ |
| 276 | Initiates a :ref:`SysCommandWorker` session in this class ``.session``. |
| 277 | It then proceeds to poll the process until it ends, after which it also |
| 278 | clears any printed output if ``.peek_output=True``. |
| 279 | """ |
| 280 | if self.session: |
| 281 | return True |
| 282 | |
| 283 | with SysCommandWorker( |
| 284 | self.cmd, |
no outgoing calls
no test coverage detected