Skip to content Skip to sidebar Skip to footer

Why Do These Print() Calls Appear To Execute In The Wrong Order?

weird.py: import sys def f (): print('f', end = '') g() def g (): 1 / 0 try: f() except: print('toplevel', file = sys.stderr) Python session: Python 3.4.2 (

Solution 1:

Because stdout and stderr are line buffered. They buffer characters and only flush when you have a complete line.

By setting end='' you ensure there is no complete line and the buffer isn't flushed until later when the Python interactive interpreter outputs >>> and flushes the buffer explicitly.

If you remove file=sys.stderr you output to sys.stdout again, and you printed toplevel\n as print() adds a newline, thus flushing the sys.stdout buffer.

You can explicitly force a flush by setting the flush=True argument to the print() function (Python 3.3 and up) or by calling sys.stdout.flush().

Post a Comment for "Why Do These Print() Calls Appear To Execute In The Wrong Order?"