2

I'm trying to make a while True-loop that repeatedly prints a string:

from time import sleep
while True:
    sleep(1)
    print("test", end="")

But it doesn't print anything when running it with VSC. Running it with the IDLE works for me, a friend also tried it and for him, it's the other way round.

Why does this happen?

martineau
  • 119,623
  • 25
  • 170
  • 301
Asgard
  • 81
  • 2
  • 10

2 Answers2

1

This is a duplicate of Does "time.sleep()" not work inside a for loop with a print function using the "end" attribute?, the output needs to be forced using print("test", end="", flush=True)

Asgard
  • 81
  • 2
  • 10
  • 2
    If it is a duplicate, then close it as a duplicate. Don't post a link to the duplicate as an answer. – ChrisMM Jan 12 '22 at 18:34
1

Python's stdout is buffered, meaning that prints to stdout don't appear on the console until a newline is printed, the buffer is full, or if the buffer is flushed.

You have three options:

  1. Get rid of the end parameter in the print() statement, as print() statements implicitly add newlines.
  2. Flush the buffer using sys.stdout.flush():
import sys
from time import sleep

while True:
    sleep(1)
    print("test", end="")
    sys.stdout.flush()
  1. Use flush=True in the print() statement.
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33
  • 2
    Just adding ```flush=True``` also works, my question is a duplicate of https://stackoverflow.com/questions/56896710/does-time-sleep-not-work-inside-a-for-loop-with-a-print-function-using-the/56896956 – Asgard Jan 12 '22 at 18:32
  • None of these work running via the vscode tester. Do you know how make them work there? – Mote Zart May 18 '22 at 21:17
  • I'm not sure. I would post a new question if I were you. – BrokenBenchmark May 18 '22 at 21:20