简体   繁体   中英

Why does Python print exceptions to the console before print() output

I'm writing a pretty lengthy function that reads in a CSV file and loops through the rows and checks that they are of an expected format, raising an exception if it finds one that is not.

For each row that is of the expected format, it prints a message to the console (using the print function) saying that the row is valid. Otherwise the error will be raised.

What I would expect to see is a series of messages saying the first X rows are valid, followed by an exception if it hits an error, but instead it prints the exception, then prints the messages, despite the fact they were called from previous iterations of the loop.

Can anyone explain why this would be as I can't wrap my head around it?

Take this short, basic example I've created:

letters = ['a','b','c']
for letter in letters:
    if letter == 'a' or letter == 'c':
        print ("Valid letter, '" + letter + "' found. Keep going.")
    else:
        raise Exception("Invalid letter, '" + letter + "' found. Break program.")

It produces the following output:

>>> >>> ... ... ... ... ... Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
Exception: Invalid letter, 'b' found. Break program.
Valid letter, 'a' found. Keep going.
>>> 

What I want is for the messages to be printed first, as they appear in the code, and the exception to be printed at the end when the code is stopped, otherwise it gets lost among a load of printed messages. It seems to be just for loops (in that if I print something before the loop, it gets printed before the exception). Can anyone offer any insight?

Exceptions are printed through standard error stream, not standard output. Depending on the terminal, both outputs aren't always synced.

You could flush output after printing:

print ("Valid letter, '" + letter + "' found. Keep going.",flush=True)

another option would be to write to standard error for your messages, which isn't a bad idea if you're planning to redirect output to a file, disregarding the messages

sys.stderr.write("Valid letter, '{}' found. Keep going.\n".format(letter))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM