How do terminal programs update progress smoothly on one line?
Asked by
stairwell_echo
I'm trying to understand how terminal programs such as Fedora's package manager update a download status without printing a new line for every update. The progress indicator changes in place, for example from [ ] | 00m00s to [ ] | 01m00s, while keeping everything on one line. How does that work? I'm learning Python and want to make a smooth T-Rex runner game inside the terminal, so I need to learn how to refresh the display without flickering or leaving old frames behind.
Answers
The basic trick is a carriage return, written as r. It moves the cursor back to the beginning of the current line without starting a new line, so the next output overwrites the previous one. In Python, you can do something like print(f'Progress: {value}%', end='r', flush=True). Using flush=True makes the update appear immediately instead of waiting in a buffer. If the new text can be shorter than the old text, clear the line first or pad the output with spaces.
Reply to this answer
For moving around the terminal more generally, programs use terminal control sequences. Tools such as tput can clear the screen, move the cursor, or erase part of a line. The terminfo database helps choose the correct sequences for the current terminal. In Python, the built-in curses module provides higher-level terminal control and is a better choice for a game with multiple moving objects, keyboard input, and screen redrawing.
Reply to this answer
Add your answer
Answers are reviewed before publication.
sewing_room_: CR means carriage return: move to the start of the line. LF means line feed: move down to the next line. A normal newline usually performs both actions.