我有一个 Django 管理命令,它执行大量处理,因此我让它以百分比形式输出进度。我想使用答案中描述的技术here https://stackoverflow.com/questions/5290994/python-remove-and-replace-printed-items or here https://stackoverflow.com/questions/3249524/print-in-one-line-dynamically。我意识到来自 Django 文档 https://docs.djangoproject.com/en/1.8/howto/custom-management-commands/ that sys.stdout
需要替换为self.stdout
当在管理命令中使用时,但我仍然没有运气。它是 python 2.7,所以我不能给出end
夸格到print
。这是我尝试过的事情之一handle
命令对象的:
i = 0
for thing in query:
self.stdout.write("\r%%%s" % (100 * float(i) / float(query.count()))
i += 1
我尝试过类似问题的答案中描述的其他几种技术,包括使用ANSI 转义序列 https://en.wikipedia.org/wiki/ANSI_escape_code。 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)
参考
我跟着这个问题 https://code.djangoproject.com/ticket/19593几年前有人开了,这个所以线程 https://stackoverflow.com/questions/881696/unbuffered-stdout-in-python-as-in-python-u-from-within-the-program;请参阅更长的详细信息和其他解决方案,例如python -u 选项 https://docs.python.org/2/using/cmdline.html#cmdoption-u.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)