Home:ALL Converter>Iterating over subprocess output results in non-zero exit code when breaking out of the loop

Iterating over subprocess output results in non-zero exit code when breaking out of the loop

Ask Time:2021-09-22T05:32:01         Author:Johnny Baloney

Json Formatter

The following snippet results in the subprocess finishing with zero exit code:

with subprocess.Popen("print.sh", stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
    for line in iter(process.stdout):
        break
        print(line)
    process.wait()
    print(f'Subprocess exit code: {process.returncode}')

# Subprocess exit code: 0

whereas when TextIOWrapper is used the exit code is non-zero:

with subprocess.Popen("print.sh", stdout=subprocess.PIPE, stderr=subprocess.STDOUT) as process:
    for line in io.TextIOWrapper(process.stdout, encoding="utf-8"):
        break
        print(line)
    process.wait()
    print(f'Subprocess exit code: {process.returncode}')

# Subprocess exit code: -13

What is the reason for the non-zero exit code in the second snippet?

Python 3.7.9

Author:Johnny Baloney,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/69275783/iterating-over-subprocess-output-results-in-non-zero-exit-code-when-breaking-out
yy