Why do these print () calls appear 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 (v3.4.2:ab2c023a9432, Oct 6 2014, 22:16:31) [MSC v.1600 64 bit (AM
D64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import weird
toplevel
f>>>
Why does "toplevel" print before "f"?
This does not happen if end = ''
or file = sys.stderr
.
source to share
Because stdout and stderr are strings. They buffer characters and only hide when you have a full string.
By setting end=''
, you make sure there is no full line and the buffer does not flush longer when the interactive Python interpreter outputs >>>
and explicitly flushes the buffer.
If you delete file=sys.stderr
, you are back to again sys.stdout
, and you typed toplevel\n
as print()
, adding a new line, thereby flushing the buffer sys.stdout
.
You can explicitly force a reset by setting an argument flush=True
to a function print()
(Python 3.3 and up) or by calling sys.stdout.flush()
.
source to share