Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/355.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django管理命令中的动态单行输出_Python_Django_Printing - Fatal编程技术网

Python Django管理命令中的动态单行输出

Python Django管理命令中的动态单行输出,python,django,printing,Python,Django,Printing,我有一个Django管理命令,它执行相当多的处理,所以我让它以百分比的形式输出它的进度。我想使用答案或中描述的技巧。我知道当在管理命令中使用时,sys.stdout需要替换为self.stdout,但我仍然运气不佳。它是Python2.7,所以我不能将结尾kwarg赋予打印。下面是我在命令对象的句柄中尝试过的一件事: i = 0 for thing in query: self.stdout.write("\r%%%s" % (100 * float(i) / float(query.c

我有一个Django管理命令,它执行相当多的处理,所以我让它以百分比的形式输出它的进度。我想使用答案或中描述的技巧。我知道当在管理命令中使用时,
sys.stdout
需要替换为
self.stdout
,但我仍然运气不佳。它是Python2.7,所以我不能将
结尾
kwarg赋予
打印
。下面是我在命令对象的
句柄中尝试过的一件事:

i = 0
for thing in query:
    self.stdout.write("\r%%%s" % (100 * float(i) / float(query.count()))
    i += 1
我已经尝试了在回答类似问题时所描述的几种其他技巧,包括使用。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)
参考文献
我发现几年前有人开过店;有关详细信息和其他解决方案,请参见。

谢谢!我一直在做
write
,没有
flush()
ending='\r'
,还把头发拔了出来!