Why does time () below 0.25 skip animation in Python?

This code works as expected. Output:

Loading Loading. Loading.. Loading... 

code:

 done = False count = 0 while not done: print '{0}\r'.format("Loading"), time.sleep(0.25) print '{0}\r'.format("Loading."), time.sleep(0.25) print '{0}\r'.format("Loading.."), time.sleep(0.25) print '{0}\r'.format("Loading..."), time.sleep(0.25) count += 1 if count == 5: done = True 

And this code does not do this. Output:

 Loading. Loading... 

code:

 done = False count = 0 while not done: print '{0}\r'.format("Loading"), time.sleep(0.125) print '{0}\r'.format("Loading."), time.sleep(0.125) print '{0}\r'.format("Loading.."), time.sleep(0.125) print '{0}\r'.format("Loading..."), time.sleep(0.125) count += 1 if count == 5: done = True 

Why does the time function seem to skip every second print statement if it's less than 0.25?

+5
source share
1 answer

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.

+5
source

Source: https://habr.com/ru/post/1239997/


All Articles