Read up to `n` bytes from the stream. If `n` is not provided or set to -1, read until EOF, then return all read bytes. If EOF was received and the internal buffer is empty, return an empty bytes object. If `n` is 0, return an empty bytes object immediately.
(self, n=-1)
| 682 | return chunk |
| 683 | |
| 684 | async def read(self, n=-1): |
| 685 | """Read up to `n` bytes from the stream. |
| 686 | |
| 687 | If `n` is not provided or set to -1, |
| 688 | read until EOF, then return all read bytes. |
| 689 | If EOF was received and the internal buffer is empty, |
| 690 | return an empty bytes object. |
| 691 | |
| 692 | If `n` is 0, return an empty bytes object immediately. |
| 693 | |
| 694 | If `n` is positive, return at most `n` available bytes |
| 695 | as soon as at least 1 byte is available in the internal buffer. |
| 696 | If EOF is received before any byte is read, return an empty |
| 697 | bytes object. |
| 698 | |
| 699 | Returned value is not limited with limit, configured at stream |
| 700 | creation. |
| 701 | |
| 702 | If stream was paused, this function will automatically resume it if |
| 703 | needed. |
| 704 | """ |
| 705 | |
| 706 | if self._exception is not None: |
| 707 | raise self._exception |
| 708 | |
| 709 | if n == 0: |
| 710 | return b'' |
| 711 | |
| 712 | if n < 0: |
| 713 | # This used to just loop creating a new waiter hoping to |
| 714 | # collect everything in self._buffer, but that would |
| 715 | # deadlock if the subprocess sends more than self.limit |
| 716 | # bytes. So just call self.read(self._limit) until EOF. |
| 717 | joined = bytearray() |
| 718 | while block := await self.read(self._limit): |
| 719 | joined += block |
| 720 | return joined.take_bytes() |
| 721 | |
| 722 | if not self._buffer and not self._eof: |
| 723 | await self._wait_for_data('read') |
| 724 | |
| 725 | # This will work right even if buffer is less than n bytes |
| 726 | data = self._buffer.take_bytes(min(len(self._buffer), n)) |
| 727 | |
| 728 | self._maybe_resume_transport() |
| 729 | return data |
| 730 | |
| 731 | async def readexactly(self, n): |
| 732 | """Read exactly `n` bytes. |