def disable_stdout_buffering():
# Appending to gc.garbage is a way to stop an object from being
# destroyed. If the old sys.stdout is ever collected, it will
# close() stdout, which is not good.
gc.garbage.append(sys.stdout)
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
# Then this will give output in the correct order:
disable_stdout_buffering()
print "hello"
subprocess.call(["echo", "bye"])
वर्ष sys बचत के बिना।stdout, disable_stdout_buffering() idempotent नहीं है, और कई कॉल इस तरह एक त्रुटि में परिणाम होगा:
Traceback (most recent call last):
File "test/buffering.py", line 17, in <module>
print "hello"
IOError: [Errno 9] Bad file descriptor
close failed: [Errno 9] Bad file descriptor
एक और संभावना है:
def disable_stdout_buffering():
fileno = sys.stdout.fileno()
temp_fd = os.dup(fileno)
sys.stdout.close()
os.dup2(temp_fd, fileno)
os.close(temp_fd)
sys.stdout = os.fdopen(fileno, "w", 0)
(gc.garbage को जोड़ना इतना अच्छा नहीं है । विचार है क्योंकि यह जहां unfreeable चक्र डाल पाने के है, और आप उन लोगों के लिए जाँच करने के लिए चाहते हो सकता है)
स्रोत
2010-09-09 15:37:53
'पायथन 3 में प्रिंट 'के लिए, देखें [इस उत्तर] (http://stackoverflow.com/a/14729823/918959)। –
मुझे लगता है कि '-u' की कमी यह है कि यह संकलित बाइटकोड के लिए या' __main __। Py' फ़ाइल के साथ प्रविष्टि बिंदु के रूप में ऐप्स के लिए काम नहीं करेगा। – akhan