By default, many Python commands and scripts display final output and intermediate messages directly in terminal or stdout when executed. Often you may want to disable output buffering in Python. In this article, we will learn how to do this. There are several ways to do this.
How to Disable Output Buffering in Python
Here are the different ways to disable output buffering in Python.
1. Using -u switch
One of the simplest ways to disable output buffering is to run python commands with -u switch.
$ python -u script_name
Alternatively, you can add the -u switch in your python script, when you define the execution environment.
#!/usr/bin/env python -u
But this method works only on the specific script or command where the -u switch is used. The output buffering will be re-enabled after the script is executed.
2. Set PYTHONUNBUFFERED
You can also set the environment variable PYTHONUNBUFFERED to true in your bash profile or other places where environment variables are defined.
If the above environment variable has non empty value, it will force stdout and stderr streams to be unbuffered.
If you set this variable in bash profile or other such files, then it will permanently disable output buffering, unless you revert the changes.
3. Using sys.stdout
You can also set sys.stdout variable to the following wrapper to disable output buffering.
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
Alternatively, you can define the following unbuffering wrapper that flushes buffer for specific functions such as write() and writelines().
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) print 'Hello'
4. Using flush argument
Since python 3.3, print() function supports flush argument that can be used to flush buffers.
print('Hello World!', flush=True)
In this article, we have learnt how to disable output buffering in Python. You can use any of the above methods but setting environment variable will permanently disable output buffering while other methods will only disable buffering during execution of specific script or command.
How to Read Large Files in Python
How to Copy File Permissions & Ownership in Linux
Display Command Output & File Contents in Column Format
How to Create Nested Directory in Python
How to Add Blank Directory in Git Repository