There is no issue with the code you posted. Something else is going on here. Are you piping to some other program that is closing the pipe?
e.g. script.py input.txt | head
or script.py input.txt | tail
If so then just store the output in a file or variable first. For example:
script.py input.txt > output.txt
head output.txt
Or...
output=$(script.py input.txt)
head <<<"$output"
If you just want to suppress the error, you can replace the end of your script with the following:
try:
for line in range(3, length):
print(line, input_lines[line], end="")
except BrokenPipeError:
pass