-1

There is too much print and I want some of the temporary prints be erased. For example, I have:

import time
for shard in range(3):
    for i in range(100):
        print("image_{} in shard_{}".format(i, shard))
        time.sleep(1)

Instead of a list of all the prints

image_0 in shard_0
image_1 in shard_0
image_2 in shard_0
image_3 in shard_0

I want to see them printed once and then be replaced by the next print.

image_0 in shard_0
image_1 in shard_0
image_2 in shard_0

At the end I shall only have

image_99 in shard_0
image_99 in shard_1
image_99 in shard_2

on the screen.

How could I achieve that?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
zheyuanWang
  • 1,158
  • 2
  • 16
  • 30

3 Answers3

2

I think you have misunderstood what "flushing the output buffer" means. I doesn't erase what has previously been printed. It just means "print immediately, without waiting for a whole line (or file worth) of output."

An example where flushing can matter is when you print out several things on a single line, with a delay in between them:

import time

for i in range(10):
    print(i, end="")
    time.sleep(1)

On many consoles this won't print anything for ten seconds, then you'll see 0123456789 appear all at once. But if you add flush=True to the print call, you'll see each number appear separately, one after the other, with a one second delay in between. You still get 0123456789 on one line, but it builds up gradually. (Note that the consoles built in to some IDEs may not do line buffering in the normal ways a real terminal will, so your mileage may vary. Real consoles are much more consistent.)

If you're printing full lines with a newline at the end (which is the default for print), using flush usually isn't necessary because most terminals are line-buffered. That means they'll flush themselves automatically at the end of every line, even without flush=True explicitly demanding a flush after its output.

Blckknght
  • 100,903
  • 11
  • 120
  • 169
1

Try this:

import time
for shard in range(3):
    for i in range(100):
        print("image_{} in shard_{}\r".format(i,shard),end = "")
        time.sleep(1)
    print()
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ClassHacker
  • 394
  • 3
  • 11
0

Try:

for i in range(3):
    print("{}\r".format(i), end="")

print("Hello\r", end="")
print("World\r", end="")

The output will be World.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dr. Prof. Patrick
  • 1,280
  • 2
  • 15
  • 27