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?
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With