Read up to ``max_bytes`` from ``path``. Caps disk I/O so a symlink to /dev/zero or a corrupted stat'd size can't OOM the process. When ``max_bytes`` is None, behaves like ``read_bytes``.
(path: Path, max_bytes: int | None = None)
| 121 | # --------------------------------------------------------------------------- |
| 122 | |
| 123 | def read_file_bytes(path: Path, max_bytes: int | None = None) -> bytes: |
| 124 | """Read up to ``max_bytes`` from ``path``. |
| 125 | |
| 126 | Caps disk I/O so a symlink to /dev/zero or a corrupted stat'd size can't |
| 127 | OOM the process. When ``max_bytes`` is None, behaves like ``read_bytes``. |
| 128 | """ |
| 129 | if max_bytes is None: |
| 130 | return path.read_bytes() |
| 131 | size = path.stat().st_size |
| 132 | read_size = min(size, max_bytes) |
| 133 | with path.open("rb") as fh: |
| 134 | return fh.read(read_size) |
| 135 | |
| 136 | |
| 137 | # --------------------------------------------------------------------------- |