Cause
Depending on the platform, Python buffers output to varying degrees. For example, on Mac OSX there is no way out even for your version with a hibernation in increments of 0.25 seconds.
Manual flushing
Manual flushing should work:
import sys import time done = False count = 0 while not done: for n in range(4): print '{0}\r'.format("Loading" + n * '.'), sys.stdout.flush() time.sleep(0.125) print ' ' * 20 + '\r', count += 1 if count == 5: done = True
You need to clear the output with sys.stdout.flush() . You also need to print empty spaces to make back and forth dots:
print ' ' * 20 + '\r',
More minimal and refined
This is shortened and slightly more general in terms of the text shown:
import sys import time text = 'Loading' for _ in range(5): for n in range(4): print '{0}\r'.format(text + n * '.'), sys.stdout.flush() time.sleep(0.25) nspaces = len(text) + n print ' ' * nspaces + '\r',
Run without buffering from the command line
You can delete the line:
sys.stdout.flush()
if you run your script with the -u option:
python -u script_name.py
Note This will affect all print statements.
source share