本文介绍了在Django管理命令中添加了虚假的换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python 3.5.0上运行Django v1.10:

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)

预期输出: p>

Expected output:

hello world

实际输出:

hello 

world

如何正确传递结束字符?我目前使用明确设置的解决方法:

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

 self.stdout.ending = ''

但是这个黑客意味着你没有获得打印功能的所有功能,你必须使用 self.stdout。写入并手动准备字节。

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.

推荐答案

显式设置 self.stdout.ending 时,打印命令按预期工作。

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

file = self.stdout.ending self.stdout ,因为这是一个 django.core.management.base.OutputWrapper 的实例。

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)

返回

hello world

这篇关于在Django管理命令中添加了虚假的换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 15:39