This is a minimal possible example of the problem I have encountered:
Python script:
#!/usr/bin/env python3
import sys
import os
import fileinput
# I
line = sys.stdin.readline()
while line:
exit(0)
line = sys.stdin.readline()
# II
for line in fileinput.input():
exit(0)
pass
# III
stdin_input_iter = enumerate(sys.stdin)
try:
next(stdin_input_iter)
exit(0)
except StopIteration:
exit(0)
Shell script:
set -o pipefail
yes | ./test.py ; echo $?
The result of running this shell script:
141
All of the versions: I, II, and III in the Python script result in exit code 141 while I would like them to simply exit with 0.
Intuitively I understand that my Python script wants to exit(0) while yes is still writing to the Python's stdin and due to the behavior enforced by set -o pipefail, this results in the 141 exit code.
The only solution to overcome this problem I have found so far is to simply continue reading the stdin until the input is exhausted but I am wondering if there is any other solution for my Python script to prevent the exit code 141 from happening.