Python dynamic update in-place Terminal text
Cross-platform, dynamically updating text is enabled in Python print()
with end='\r'
, like:
print('dynamic text', end='\r')
The dynamically updating text will immediately display.
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 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.
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.
Here’s an example:
from time import sleep
N=12
for i in range(N):
sleep(0.5)
print(f"{i/N*100:.1f} %", end="\r")
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.