सबसे पहले, self.stdout
django.core.management.base.OutputWrapper
कमांड का एक उदाहरण है। इसके write
एक str
उम्मीद नहीं 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
उदाहरण है और समाप्ति 012 है।
इसके अलावा, self.stdout
के साथ सही ढंग से काम करता है जब मैं self.stdout.ending = ''
स्पष्ट रूप से सेट करता हूं; हालांकि ऐसा करने का अर्थ यह हो सकता है कि self.stdout.write
का उपयोग करने वाले अन्य कोड को न्यूलाइन डालने की उम्मीद है, असफल हो जाएगा।
आपके मामले में, मैं क्या चाहते हैं Command
के लिए एक print
विधि को परिभाषित करने के लिए है:
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')
क्या आपका उपयोग-मामला संविधान आदि के आधार पर एक संपूर्ण पाठ स्ट्रिंग बनाने की लाइनें अधिक लंबा है। कारण मैं पूछता हूं कि अगर पूरी स्ट्रिंग अग्रिम में जानी जाती है, जैसे "हैलो वर्ल्ड" के मामले में न्यूलाइन एंडिंग कैरेक्टर पर नियंत्रण प्राप्त करने के लिए stdout.write के बिना प्रिंट का उपयोग करते समय आसानी से पूर्ण लाइन के रूप में लिखा जा सकता था। तो यह मानते हुए कि आप समय से पहले पाठ को नहीं जानते हैं, क्या आप स्ट्रिंग एपेंड द्वारा टेक्स्ट नहीं बना सकते हैं जब तक पूरा टेक्स्ट प्रिंटिंग के लिए तैयार न हो जाए। –
संबंधित: http://stackoverflow.com/questions/31926422/redirection-in-django-command-called-from-another-command-results-in-extraneous। और यदि आपको कोई समाधान नहीं मिलता है, तो मैं आपको जिस तरह से चाहूं व्यवहार करने के लिए अस्थायी रूप से 'प्रिंट' और/या' self.stdout 'पैचिंग करने के लिए एक सजावट या संदर्भ प्रबंधक लिखने की अनुशंसा करता हूं। –
मुझे यह नहीं मिलता कि 'self.stdout.ending =' '' 'का उपयोग कैसे करें [आप] प्रिंट फ़ंक्शन और इसकी सभी अच्छी सुविधाओं का उपयोग करने से रोकता है "। आप अभी भी 'प्रिंट' का उपयोग कर सकते हैं, और आउटपुट आप उम्मीद करेंगे कि समस्या क्या है? – Louis