5
from sys import argv, stdout as cout
from time import sleep as sl
print("Rewinding.......",end = '') # If end is given output isn't flushed. But why?
cout.flush()
for i in range(0,20):
    sl(0.2)
    print(".",end='',flush = True) #No output is printed if flush wasn't specified as true.

print("Done") #Output is by default flushed here

When I specified end and sleep, I noticed that output wasn't flushed until next print where it was by default flushed.

Why does this happen? I had to manually flush the output.

Tarun Maganti
  • 3,076
  • 2
  • 35
  • 64

1 Answers1

8

In fact this is the default behavior of the underlying stdio functions.

When the output is to console, the stream will be automatically flushed when a newline is encountered, but not other characters.

If the output is not a console, then even newline won't trigger a flush.

If you want to make sure about flush, you can tell the print() explicitly:

print("Rewinding.......",end = '',flush=True)
llllllllll
  • 16,169
  • 4
  • 31
  • 54
  • "When the output is to console, the stream will be automatically flushed when a newline is encountered, but not other characters." This I didn't know. Is this behaviour Python specific or any programming language specific. – Tarun Maganti Mar 03 '18 at 10:51
  • I mean to say `std::endl` also flushes output but '\n' doesn't in C++ which I know. Does it mean it's the feature of the software/feature [The underlying system] which is on the receiving end of stdout? – Tarun Maganti Mar 03 '18 at 10:53
  • This is the feature of C language `stdio.h` functions. Whether it is a console is checked by `unistd.h` function [`isatty(3)`](http://man7.org/linux/man-pages/man3/isatty.3.html) – llllllllll Mar 03 '18 at 10:56
  • So flushing is dependent on the programming language but not the system? If the library which implements print will decide when to flush or not. – Tarun Maganti Mar 03 '18 at 10:58
  • 1
    Yes, language/library specific. – llllllllll Mar 03 '18 at 10:59
  • However, Does python's print use C's stdio? If it does, doesn't it mean whenever C flushes automatically {with wahtever parameter it chooses to do so}, the CPython will have similar functionality? Does it work like that? or is there some other mechanism on which Python works? – Tarun Maganti Mar 03 '18 at 11:03
  • 1
    They use `stdio` you can read their source code. But those are indeed implementation details, not documented. The only way to know details at this level is to read the source code. Of course Python can add some additional stuff, you can't simply assume they are *exactly* the same. – llllllllll Mar 03 '18 at 11:06
  • I recently faced this issue in Python 3.9.13 but earlier I never use `Flush=True` argument. so wonder why it worked earlier and now it didn't. – chintan s Dec 21 '22 at 13:23