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