Python dynamically updating in-place Terminal text

less than 1 minute read

Technique

Dynamically updating text is enabled in Python print() by print('my dynamic text', end='\r') The dynamically updating text will immediately display on Windows, Mac and Linux.

  • Be sure not to print more than 80 characters in a line, because the default Terminal & Command Prompt width is 80 characters and this method breaks if the line wraps.

Advantages

The advantage of this method is that previous information is not scrolled off the screen. One common use for this method is terminal text progress indicators. Of course, using special characters, pseudo-graphical dynamic terminal displays are also possible.

Example

Notice the Python 2.7 method is much messier, one of many reasons to drop Python 2 use now.

Python 3

from time import sleep

N=12

for i in range(N):
   sleep(0.5)
   print(f"{i/N*100:.1f} %", end="\r")

Python 2.7

from __future__ import print_function
from time import sleep
import sys

N=12

for i in range(N):
   sleep(0.5)
   print("{:.1f} %".format(float(i)/N*100),end="\r")
   sys.stdout.flush()

Categories:

Updated:

Leave a Comment