Files
SIA/sia/standard_io_buffer.py
2024-11-01 16:27:56 +01:00

68 lines
2.0 KiB
Python

import sys
from .io_buffer import IOBuffer
class StandardIOBuffer(IOBuffer):
"""
IOBuffer implementation that uses system standard input/output.
This class provides direct access to stdin/stdout for IO operations.
It implements a basic line-based input buffer to handle cases where
multiple reads are needed to process all available input.
"""
def __init__(self):
"""Initialize the standard IO buffer."""
self._input_buffer: str = ""
def read(self) -> str:
"""
Read available input from stdin.
If there is buffered input from a previous read, return that first.
Otherwise, try to read new input from stdin if available.
Returns:
str: Content read from stdin, or empty string if no input available
"""
# Return and clear any existing buffered input
if self._input_buffer:
content = self._input_buffer
self._input_buffer = ""
return content
# Check if there's input available
if not sys.stdin.isatty() and sys.stdin.readable():
try:
content = sys.stdin.read()
if content:
return content
except Exception:
pass # Ignore any read errors
return ""
def write(self, content: str) -> None:
"""
Write content to stdout.
Args:
content: String content to write
"""
if not content:
return
try:
sys.stdout.write(content)
sys.stdout.flush()
except Exception:
pass # Ignore write errors
def buffer_length(self) -> int:
"""
Get the current length of buffered input.
Returns:
int: Number of characters in the input buffer
"""
return len(self._input_buffer)