2015-06-20 64 views
4

我有一个Django管理命令,它执行了相当多的处理,所以我以百分比形式输出它的进度。我想要使​​用答案herehere中所述的技术。我知道from the Django docssys.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管理命令打印输出的方式有什么特别之处吗?我怎样才能达到我期待的效果?

回答

1

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

+0

感谢您的支持!我一直在用'ending ='\ r''写''而不用'flush()'并且拉出我的头发! – theannouncer