开发者

Having trouble with time.sleep

开发者 https://www.devze.com 2022-12-30 03:44 出处:网络
When I run, for example: print(\"[\",end=\" \") time.sleep(1) print(\"=\",end=\" \") time.sleep(1) print(\"=\",end=\" \")

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)
prin开发者_StackOverflow社区t("=",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?


Try flushing stdout after each print:

import sys

print("=",end=" ")
sys.stdout.flush()


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.


sys.stdout.flush()


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

0

精彩评论

暂无评论...
验证码 换一张
取 消