Python dynamically updating in-place Terminal text

Technique

Dynamically updating text is enabled in Python print() by

  1. starting or ending the string with \r
  2. using the end="" argument

Both of these are required for the dynamically updating text to immediately display on Windows, Mac and Linux.

  • ending the string with \r preserves the last prior print() line, which can be more appropriate in some scenarios.
  • 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

"""
Dynamically updating progress indicator.
Overwrites text in place w/o wasting screen space with progress printouts.
"""
from time import sleep

N=12

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

Notes

This method requires Python 3 – Python 2.7 is possible via more complex methods.

Categories:

Updated:

Leave a Comment