The following script raises BrokenPipeError: [Errno 32] Broken pipe
, when piped to a command like head
(unless the number of lines to head exceeds the number of lines printed by the Python script).
for i in range(16386):
print("")
$ python test-pipe.py | head -1
Traceback (most recent call last):
File "test-pipe.py", line 2, in <module>
print("")
BrokenPipeError: [Errno 32] Broken pipe
My understanding (from this answer and the answers to this question) is that an error is raised if a pipe is closed before the Python process has finished writing to it.
However, if I decrement the iterated range with one to 16385, the error is not raised (not sure if this threshold is the same on al machines so maybce just try a high and low number to reproduce). I initially thought this might be related to the pipe buffer size, but that is 64K for me (according to M=0; while printf A; do >&2 printf "\r$((++M)) B"; done | sleep 999
, so that doesn't seem to be the reason.
Why is the occurrenceBrokenPipeError
dependent on the size of what is being piped?
This is with Python 3.8.1 on Linux 5.4.15-arch1-1.
:
command instead of thehead -1
command.python3 -c "for i in range(10000): print(i)" | : </dev/tcp/unix.stackexchange.com/https
. If you double/triple the range, the python with fail with Broken Pipe.