Home >Backend Development >Python Tutorial >How Can I Disable Output Buffering for sys.stdout in Python?
Disabling Output Buffering in Python's Interpreter for sys.stdout
Python's interpreter enables output buffering by default for sys.stdout, a file-like object that accepts standard output.
Disabling Buffering Methods:
To disable output buffering, there are several approaches:
python -u [script.py]
class Unbuffered(object): def __init__(self, stream): self.stream = stream def write(self, data): self.stream.write(data) self.stream.flush() def writelines(self, datas): self.stream.writelines(datas) self.stream.flush() def __getattr__(self, attr): return getattr(self.stream, attr) import sys sys.stdout = Unbuffered(sys.stdout)
Setting this variable to a non-empty value disables buffering:
export PYTHONUNBUFFERED=1
This method involves opening a new file descriptor without buffering:
import os sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Additionally, as mentioned in the question, global flags can be set programmatically during execution. However, there doesn't appear to be an explicit global flag that disables output buffering.
The above is the detailed content of How Can I Disable Output Buffering for sys.stdout in Python?. For more information, please follow other related articles on the PHP Chinese website!