Python dynamically updating in-place Terminal text

less than 1 minute read

Cross-platform, dynamically updating text is enabled in Python print() with end='\r', like:

print('my dynamic text', end='\r')

The dynamically updating text will immediately display on Windows, Mac and Linux.

Don’t allow the printed line length to exceed the Terminal/Command Prompt width. This method breaks if the line wraps.

Retrieve the maximum line width (Linux, Mac, Windows) with Python os.get_terminal_size:

import os

width, height = os.get_terminal_size()

or get terminal width from the command line:

python -c "import os; print(os.get_terminal_size()[0])"

Typically the terminal/command prompt is 80 or 100 characters wide.

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. Using special characters, pseudo-graphical dynamic terminal displays are also possible, or use Python curses.

Example Python code

from time import sleep

N=12

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

Notes

Note that you canNOT create an actual new terminal session windows from curses. curses.newwin() “new window” is inside the “screen”, which is your existing Terminal.

Leave a Comment