首先,self.stdout
是一个django.core.management.base.OutputWrapper
命令实例。它write
期望一个str
, not bytes
,因此您可以使用
self.stdout.write('hello ', ending='')
self.stdout.write('world')
实际上self.stdout.write
确实接受字节,但只有当它ending
是一个空字符串时 - 那是因为它的write
方法已定义
def write(self, msg, style_func=None, ending=None):
ending = self.ending if ending is None else ending
if ending and not msg.endswith(ending):
msg += ending
style_func = style_func or self.style_func
self._out.write(force_str(style_func(msg)))
如果ending
为真,则如果是实例且结尾是,msg.endswith(ending)
则将失败。msg
bytes
str
此外,当我明确设置时, print
withself.stdout
确实可以正常工作;self.stdout.ending = ''
但是这样做可能意味着其他使用self.stdout.write
期望它插入换行符的代码会失败。
在您的情况下,我要做的是为以下定义一个print
方法Command
:
from django.core.management.base import OutputWrapper
class PrintHelper:
def __init__(self, wrapped):
self.wrapped = wrapped
def write(self, s):
if isinstance(self.wrapped, OutputWrapper):
self.wrapped.write(s, ending='')
else:
self.wrapped.write(s)
class Command(BaseCommand):
def print(self, *args, file=None, **kwargs):
if file is None:
file = self.stdout
print(*args, file=PrintHelper(file), **kwargs)
def handle(self, *args, **options):
self.print('hello ', end='')
self.print('world')
你可以把它变成你自己的BaseCommand
子类——你也可以将它与不同的文件一起使用:
def handle(self, *args, **options):
for c in '|/-\\' * 100:
self.print('\rhello world: ' + c, end='', file=self.stderr)
time.sleep(0.1)
self.print('\bOK')