Dynamic single line output in a Django control command

I have a Django management team that does quite a bit of processing, so I have a percentage of its progress. I would like to use the technique described in the answers here or here . I know from the Django docs that sys.stdoutneed to be replaced with self.stdoutwhen used inside the control command, m is still out of luck. This is python 2.7, so I can not give endkwarg print. Here is one of the things I tried in the handleCommand object:

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

I tried several other methods described in answers to similar questions, including the use of ANSI escape sequences . Is there anything special about how Django control commands output output? How can I achieve the effect I'm looking for?

+4
source share
1 answer

TL; DR

The output of stdout is buffered by default, so do a manual routing:

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)

Link

I followed this question that someone opened a few years ago, and this SO thread ; for more details as well as for other solutions like the python -u option .

+1
source

All Articles