2015-06-20 67 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