Django管理命令中的动态单行输出
问题描述:
我有一个Django管理命令,它执行了相当多的处理,所以我以百分比形式输出它的进度。我想要使用答案here或here中所述的技术。我知道from the Django docs,sys.stdout
需要用self.stdout
替换时,在管理命令中使用,但我仍然没有运气。这是蟒蛇2.7,所以我不能给end
kwarg print
。下面是我在Command对象的handle
尝试过的事情之一:Django管理命令中的动态单行输出
i = 0
for thing in query:
self.stdout.write("\r%%%s" % (100 * float(i)/float(query.count()))
i += 1
我试图在回答类似的问题,包括使用ANSI escape sequences描述了几种其它技术。 Django管理命令打印输出的方式有什么特别之处吗?我怎样才能达到我期待的效果?
答
TL;博士
标准输出输出默认情况下缓冲,所以手动冲水:
import time
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = "My shiny new management command."
def handle(self, *args, **options):
self.stdout.write("Writing progress test!")
for i in range(100):
self.stdout.write("%{}".format(i), ending='\r')
self.stdout.flush()
time.sleep(0.01)
参考
我跟着this issue有人开了几年前,和this SO thread;查看更详细的信息和其他解决方案,例如python -u option。
感谢您的支持!我一直在用'ending ='\ r''写''而不用'flush()'并且拉出我的头发! – theannouncer