Dynamic one-line output in Django management command

萝らか妹 提交于 2020-06-12 03:32:19

问题


I have a Django management command that does quite a bit of processing, so I have it outputting its progress as a percentage. I'd like to use a technique as described in the answers here or here. I'm aware from the Django docs that sys.stdout needs to be replaced with self.stdout when used inside a management command, but I'm still having no luck. It's python 2.7, so I can't give the end kwarg to print. Here's one of the things I've tried in handle of the Command object:

i = 0
for thing in query:
    self.stdout.write("\r%%%s" % (100 * float(i) / float(query.count()))
    i += 1

I've tried several other techniques described in answers to similar questions, including using ANSI escape sequences. Is there something special about the way that Django management commands print output? How can I achieve the effect I'm looking for?


回答1:


tl;dr

stdout output is buffered by default, so flush manually:

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)

Reference

I followed this issue that someone opened a few years back, and this SO thread; see both for longer details and other solutions, such as the python -u option.



来源:https://stackoverflow.com/questions/30957273/dynamic-one-line-output-in-django-management-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!