In Python 3, print can take an optional flush argument:
print("Hello, World!", flush=True)
In Python 2, after calling print, do:
import sys
sys.stdout.flush()
By default, print prints to sys.stdout (see the documentation for more about file objects).
python - How can I flush the output of the print function? - Stack Overflow
python - Usage of sys.stdout.flush() method - Stack Overflow
What does sys.stdout.flush() do? ELI5
How to control stdout buffering
Videos
In Python 3, print can take an optional flush argument:
print("Hello, World!", flush=True)
In Python 2, after calling print, do:
import sys
sys.stdout.flush()
By default, print prints to sys.stdout (see the documentation for more about file objects).
You can change the flushing behavior using the -u command line flag, e.g. python -u script.py.
-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'
Here is the relevant documentation.
Python's standard out is buffered (meaning that it collects some of the data "written" to standard out before it writes it to the terminal). Calling sys.stdout.flush() forces it to "flush" the buffer, meaning that it will write everything in the buffer to the terminal, even if normally it would wait before doing so.
Here's some good information about (un)buffered I/O and why it's useful:
http://en.wikipedia.org/wiki/Data_buffer
Buffered vs unbuffered IO
Consider the following simple Python script:
import time
import sys
for i in range(5):
print(i),
#sys.stdout.flush()
time.sleep(1)
This is designed to print one number every second for five seconds, but if you run it as it is now (depending on your default system buffering) you may not see any output until the script completes, and then all at once you will see 0 1 2 3 4 printed to the screen.
This is because the output is being buffered, and unless you flush sys.stdout after each print you won't see the output immediately. Remove the comment from the sys.stdout.flush() line to see the difference.
I'm writing a library to do some stuff with an API. I've put in some error handling to avoid the thing blowing up on the rare occasion when the API doesn't return properly using some code I found on stack exchange.
respi=requests.get(f"{burl}/{searchtype}/{iid}")
notdone=True
retries=0
while notdone:
try:
iinfo=json.loads(respi.text)
latlon=(iinfo['geo']['latitude'],iinfo['geo']['longitude'])
notdone=False
except Exception as e:
if retries==5:
print("Too many retries")
print("Exiting....")
sys.exit()
wait=(retries+1)**2
print(f'Something went wrong.... retrying in {wait} seconds')
sys.stdout.flush()
time.sleep(wait)
retries+=1
time.sleep(0.1)The question I have is, what does sys.stdout.flush() actually do here?