views:

69

answers:

4

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?

A: 

sys.stdout.flush()

msw
A: 

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

Daniel DiPaolo
+5  A: 

Try flushing stdout after each print:

import sys

print("=",end=" ")
sys.stdout.flush()
Mark Byers
+3  A: 

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.

ΤΖΩΤΖΙΟΥ
What would that do? I don't understand, I'm just a beginner. Would that still output it to the shell?
Waterfox
@Waterfox: yes, it would still output to the “terminal”. Go ahead and try it.
ΤΖΩΤΖΙΟΥ
I don't understand, what's the difference?
Waterfox
@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.
ΤΖΩΤΖΙΟΥ
Yes, yes, I understand what you mean, now. Thanks very much.
Waterfox