Output from sys.exit sometimes appears on terminal before output from print

43 Views Asked by At

Running this code multiple times, I sometimes get the expected output but otherwise I get the "End of list" caused by StopIteration first, and then the prints from the loop.

import sys

data = ['a', 'b', 'c']

def myf(*args):
    for arg in args:
        yield arg

generator_object = myf(*data)

while True:
    try:
        print(next(generator_object))
    except StopIteration:
        sys.exit('End of list')

The output I would expect every time is the one with "End of list" last, since the exception should be raised after the generator has run out of items to print. However, maybe half the time, I get this:

End of list
a
b
c

Process finished with exit code 1

Running this code multiple times looks like this:

GIF showing multiple executions

Why?

1

There are 1 best solutions below

2
SIGHUP On BEST ANSWER

The string given to sys.exit() is written to stderr whereas print() goes (by default) to stdout. Although the output is ultimately to a terminal, the order isn't guaranteed due to independent buffering of the two streams.

Documentation here