1

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.

1
  • 1
    For an explanation of why this happens, see the closely related question stackoverflow.com/q/41516177/14122. Don't have a laptop with me (for probably about two hours) so I can't immediately write up a focused version for this variant, but hopefully it's obvious after reading the link. Commented Dec 21, 2019 at 14:24

1 Answer 1

1
{ yes || :; } | ./test.py

or

./test.py < <(yes)

...will ignore any exit status from yes reflecting its inability to write to stdout.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. Does it mean that I can do nothing on the Python script's side to prevent this from happening?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.