Read from file-like object until size bytes are read. Raises ValueError if not EOF is encountered before size bytes are read. Non-blocking objects only supported if they derive from io objects. Required as e.g. ZipExtFile in python 2.6 can return less data than requested.
(fp, size, error_template="ran out of data")
| 949 | |
| 950 | |
| 951 | def _read_bytes(fp, size, error_template="ran out of data"): |
| 952 | """ |
| 953 | Read from file-like object until size bytes are read. |
| 954 | Raises ValueError if not EOF is encountered before size bytes are read. |
| 955 | Non-blocking objects only supported if they derive from io objects. |
| 956 | |
| 957 | Required as e.g. ZipExtFile in python 2.6 can return less data than |
| 958 | requested. |
| 959 | """ |
| 960 | data = bytes() |
| 961 | while True: |
| 962 | # io files (default in python3) return None or raise on |
| 963 | # would-block, python2 file will truncate, probably nothing can be |
| 964 | # done about that. note that regular files can't be non-blocking |
| 965 | try: |
| 966 | r = fp.read(size - len(data)) |
| 967 | data += r |
| 968 | if len(r) == 0 or len(data) == size: |
| 969 | break |
| 970 | except BlockingIOError: |
| 971 | pass |
| 972 | if len(data) != size: |
| 973 | msg = "EOF: reading %s, expected %d bytes got %d" |
| 974 | raise ValueError(msg % (error_template, size, len(data))) |
| 975 | else: |
| 976 | return data |
no test coverage detected