There are plenty of methods to this.
If you are working with Python 2.X, you need to call sys.stdout.flush()
after every print.
If you are using python 3 then you can get it done by doing
print(#,sep = ' ', flush=True)
You can disable the buffering completely if you run python with -u option: python -u script.py
If you run your script directly i.e. ./script.py
then specify it in the shebang line: #!/usr/bin/env python -u
.
The other way to do it is to set env variable PYTHONUNBUFFERED
from the bash shell:
export PYTHONUNBUFFERED="aa"
Adding more details to cause of the issue:
Stdout in Python is line buffered. Meaning if you had skipped the "," in your print your output will be printed as expected. But when the output is printed in the same line then it will be flushed only if there is a new line or the buffer is full. In case you redirect your output to a file instead of terminal (python script.py >output
), output will be flushed only when the buffer is full. This can be verified if you pipe the output to cat:
python script.py | cat
In all the methods mentioned in this answer and other answers we are explicitly telling Python to not buffer but flush the output as soon as it gets it.
More research on the topic:
This behavior is not Python Specific. This is the case with printf
in C as well. It is due to glibc implementation of linux. The reasoning behind this behavior is efficiency. Because the output is buffered number of read and write operations are minimized. I found this article which gives a brief description of the same: Unix Buffering Delays