我有一个 Django 管理命令,它执行相当多的处理,所以我让它以百分比的形式输出它的进度。我想使用答案中描述的技术 here或 here .我知道 from the Django docs在管理命令中使用时,sys.stdout
需要替换为 self.stdout
,但我仍然没有运气。它是 python 2.7,所以我不能将 end
kwarg 提供给 print
。这是我在 Command 对象的 handle
中尝试过的事情之一:
i = 0
for thing in query:
self.stdout.write("\r%%%s" % (100 * float(i) / float(query.count()))
i += 1
我已经尝试了类似问题的答案中描述的其他几种技术,包括使用 ANSI escape sequences . Django管理命令打印输出的方式有什么特别之处吗?我怎样才能达到我想要的效果?
最佳答案
tl;dr
stdout 输出默认是缓冲的,所以手动刷新:
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 .
关于python - Django管理命令动态一行输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30957273/