2

When I run, for example:

print("[",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("=",end=" ")
time.sleep(1)
print("]",end=" ")

Nothing happens for 10 seconds, then the whole [ = = = = = = = = = = ] appears. How can I prevent that so that it can act as a sort of progress bar?

tzot
  • 92,761
  • 29
  • 141
  • 204
Kudu
  • 6,570
  • 8
  • 27
  • 27
  • 7
    oww, that is nasty. What about loops? They never did anything bad to deserve such blatant ignorance! Have a heart, man! – LukeN May 11 '10 at 22:42
  • possible duplicate of [Problems with sys.stdout.write() with time.sleep() in a function](http://stackoverflow.com/questions/2808832/problems-with-sys-stdout-write-with-time-sleep-in-a-function) – tzot Jun 07 '10 at 14:03

4 Answers4

5

Try flushing stdout after each print:

import sys

print("=",end=" ")
sys.stdout.flush()
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
3

Actually, a progress bar belongs to sys.stderr, which is (very conveniently and not coincidentally at all) not buffered. So I suggest you:

print("=", end=" ", file=sys.stderr)

instead.

PS a synopsis of the standard input, output and error streams in POSIX-conformant operating systems can be found in Wikipedia: Standard streams. In a few words: stdin is the input to a process; stdout is the useful output of a process, the results; stderr is for warnings, errors and out-of-band (e.g. progress bars) output.

tzot
  • 92,761
  • 29
  • 141
  • 204
  • What would that do? I don't understand, I'm just a beginner. Would that still output it to the shell? – Kudu May 12 '10 at 22:26
  • @Waterfox: yes, it would still output to the “terminal”. Go ahead and try it. – tzot May 12 '10 at 23:57
  • I don't understand, what's the difference? – Kudu May 13 '10 at 19:20
  • 1
    @Waterfox: first, using `sys.stderr` you can `print` without having to call `sys.stdout.flush` every time. Second, a progress bar is a *diagnostic* about the… progress (what else?) of a program, it's not and should not be part of the *standard output* of the program; progress bars and printing to the *standard error* are a match made in heaven. If that still confuses you, ignore everything I said after “Second,” in this comment. – tzot May 13 '10 at 20:49
  • Yes, yes, I understand what you mean, now. Thanks very much. – Kudu Jun 01 '10 at 21:24
0

sys.stdout.flush()

msw
  • 42,753
  • 9
  • 87
  • 112
0

You need to flush stdout using sys.stdout.flush() every time you want to write the updates.

Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115