About Incremental Progress Indicator in Management Commands

Use the ending="" parameter of stdout.write() in management commands to skip the new line symbol and allow the next write to add to the same line:

1
2
3
self.stdout.write(f"- {title} ", ending="")
# something with heavy processing...
self.stdout.write("✓")

For example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# myapp/management/commands/create_fake_posts.py
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    help = "Creates 1000 fake posts."

    def handle(self, *args, **options):
        self.stdout.write("=== Creating posts ===")
        for i in range(1, 1001):
            self.stdout.write(f"- Post {i} ", ending="")
            # create the post here...
            self.stdout.write("✓")
        self.stdout.write("All done!")

This will output in real time:

1
2
3
4
5
6
7
8
=== Creating posts ===
- Post 1 ✓
- Post 2 ✓
- Post 3 ✓
...
- Post 999 ✓
- Post 1000 ✓
All done!

Tips and Tricks Programming Development Django 4.x Django 3.2 Django 2.2