Having trouble with time.sleep

耗尽温柔 提交于 2019-12-11 01:51:33

问题


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?


回答1:


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.




回答2:


Try flushing stdout after each print:

import sys

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



回答3:


sys.stdout.flush()




回答4:


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



来源:https://stackoverflow.com/questions/2814933/having-trouble-with-time-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!