Search code examples
pythondjangopython-3.xstdoutdjango-management-command

Spurious newlines added in Django management commands


Running Django v1.10 on Python 3.5.0:

from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def handle(self, *args, **options):
        print('hello ', end='', file=self.stdout)
        print('world', file=self.stdout)

Expected output:

hello world

Actual output:

hello 

world

How do I correctly pass the ending character? I currently use a workaround of setting explicitly:

 self.stdout.ending = ''

But this hack means you don't get all the features of the print function, you must use self.stdout.write and prepare the bytes manually.


Solution

  • When setting self.stdout.ending explicitly, the print command works as expected.

    The line ending needs to be set in self.stdout.ending when file=self.stdout, because that is an instance of django.core.management.base.OutputWrapper.

    class Command(BaseCommand):
        def handle(self, *args, **options):
            self.stdout.ending = ''
            print('hello ', end='', file=self.stdout)
            print('world', file=self.stdout)
    

    Returns

    hello world