0

Whenever I run a method, I have included "confirmation" messages to let the user know the current process. The problem is that the two print statements print after the for loop, instead of one before and one after. See the code snippet below.

print("looping...",end="")
for x in range(100000000):
    pass
print("ok")

Here, there is a notable pause and then both print statements output to the terminal. However, when I use a self-made print function, such as:

def hprint(*args,end='\n'):
    for item in args:
        sys.stdout.write(str(item)+' ')
    sys.stdout.write(end)
    sys.stdout.flush()

The first print message is sent to the terminal, there is a pause, and then the second one follows. Why is this? What is the difference between print() and my hprint() function that causes this?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • 4
    the `flush` is the difference. [`print(...., flush=True)`](https://docs.python.org/3/library/functions.html#print) should work. the output stream is buffered for efficiency reasons. – hiro protagonist Apr 29 '22 at 11:34
  • print is buffered, if you want it to be printed immediately, use flush(). – scmanjarrez Apr 29 '22 at 11:34
  • Not sure about this, but is default `print` flushed on newlines? What happens if you put `sys.stdout.flush()` after the first `print` and what happens if you remove `end` from the first print? – Koen G. Apr 29 '22 at 11:34
  • Why did you add `sys.stdout.flush()` to your `hprint` function? Does this not already answer your question? – mkrieger1 Apr 29 '22 at 11:35
  • @mkrieger1 the question is "why", not "how." – Ian Bridges Apr 29 '22 at 11:36

0 Answers0