Python sys.stdout.flush() doesn't work

非 Y 不嫁゛ 提交于 2020-12-26 06:36:16

问题


The following code is supposed to print from 1 to 10 with 1 second intervals in between, however it is waiting for 10 seconds before actually printing anything and then it prints it all at once. How can I unbuffer the output?

import sys
import time
for count in range(10) :
   sys.stdout.write(str(count))
   sys.stdout.flush()
   time.sleep(1)

回答1:


Found the problem

import sys
import time
for count in range(10) :
   sys.stdout.write("\b%s" % count)
   sys.stdout.flush()
   time.sleep(.1)

Don't know why python is weird like this but apparently it accepted this. Your code should've worked fine but I guess python just didn't like you.




回答2:


Python 2.7, 3.2, and 3.3 all don't allow keyword arguments in your write call. Is that the proper code? The print function of course allows the end keyword and shouldn't be confused with write. Write does not add a newline character.

Removing 'end' keyword argument and testing shows the code works fine.



来源:https://stackoverflow.com/questions/12755686/python-sys-stdout-flush-doesnt-work

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