Replace a Printed Line That Overflows in Python
A hardcoded line count leaves stray rows on screen once text wraps. Here is how to count the rows the terminal really used, and the cases where that count still lies.

A terminal quote rotator prints a quote and its source, waits for Enter, then erases both and prints the next one. It works until a quote is longer than the terminal is wide. The terminal wraps the text onto an extra row, the program still moves the cursor up a fixed number of lines, and the first line of the old quote stays on screen above the new one.
This is the problem from a Stack Overflow question about replacing a printed line in Python. The asker's clear_lines(3) removes exactly three rows no matter what was printed. The asker also wondered whether it is possible to predict how many characters fit on one terminal line. It is, and the fix is to stop guessing the row count and compute it.
The approach below is based on the accepted answer, which points at shutil.get_terminal_size() and textwrap.wrap(). The answer stops at counting rows, so this article goes on to use that count and covers where the method breaks.
Why the hardcoded count fails
The helper in the question moves up and erases one row per iteration:
def clear_lines(n=1):\n LINE_UP = '\\033[1A'\n LINE_CLEAR = '\\x1b[2K'\n for i in range(n):\n print(LINE_UP, end=LINE_CLEAR)\\033[1A moves the cursor up one row and \\x1b[2K erases the whole row it is on. The loop calls clear_lines(3) before each new quote. With a short quote that is two printed rows, plus, as far as I can tell, the row the cursor drops to when the user presses Enter at input(). The 3 is a count of rows for one particular layout.
Nothing in the code knows how many rows the terminal actually used. A quote string is one print() call, but on screen it is however many rows the terminal needed to fit it. When the quote is wider than the window, the real total is higher than the constant, and the leftover row sits above the next quote.
Counting rows with shutil and textwrap
The accepted answer takes the terminal width from shutil.get_terminal_size().columns and passes it to textwrap.wrap() as width. wrap() returns a list of strings, one per row, so len() of that list is the row count:
import textwrap, shutil\n\ncol_count = shutil.get_terminal_size().columns\nwrapped = textwrap.wrap(text, width=col_count)\nnum_rows = len(wrapped)That answers the asker's question about predicting how much fits on a line. The width comes from the terminal and the wrapping comes from the standard library, with no extra dependency.
Counting alone has a weakness, covered in the last section. The terminal wraps by its own rules, and textwrap wraps by its own. If you count with one and print with the other, the two can disagree.
Print the wrapped lines yourself
The more robust variant uses the wrapped list for printing as well as counting. Each element is then one row, and the number of rows to erase is the number of rows you wrote:
import random, shutil, textwrap\n\ndef show(quote):\n cols = shutil.get_terminal_size().columns\n rows = textwrap.wrap(quote['text'], width=cols)\n rows += textwrap.wrap(quote['source'], width=cols)\n print('\\n'.join(rows))\n return len(rows)\n\nshown = 0\nwhile True:\n if shown:\n clear_lines(shown + 1)\n shown = show(random.choice(QLIST))\n if input() == 'q':\n breakThe + 1 covers the row the Enter keypress consumed at input(). That is my reading of why the original used 3 for two printed rows, so check it against your own terminal. The if shown guard also fixes something in the original loop: clear_lines(3) ran on the very first pass, when nothing had been printed yet, and moved the cursor up over whatever was above the program.
Where the count goes wrong
The row count is only as good as the width you give wrap(). If the user resizes the window between printing and clearing, the stored count describes the old layout. get_terminal_size() is read at print time, so the number is stale by the time you clear. If you can't live with that, store the count rather than recomputing it, and accept that a resize mid-quote leaves the screen messy.
The same trap applies if you call print(quote['text']) with the raw string and use wrap() only to count. The terminal breaks a long line at the column limit. textwrap breaks at whitespace by default, and splits over-long words only because break_long_words is on. The two row counts can differ, and over-counting makes you erase a row that belongs to earlier output. Printing the wrapped rows yourself avoids this.
len() measures characters, not display columns. Text with ANSI colour codes, or with wide characters such as CJK, will take more or fewer columns than its length suggests, and the wrapping will be off. If your quotes can contain those, you need a width function that understands them. I haven't tested the approach with such input, so treat it as untested there.
Finally, the cursor-up trick only reaches rows still on screen. If the output has scrolled past the top, moving up can't reach the rows above it. For anything more elaborate than replacing a few rows, a terminal UI library is a better fit than hand-written escape codes. The method here suits a short, simple loop.
This article draws on Replace a printed line when it overflows to the next line and an answer to it, on the Stack Exchange network, licensed under CC BY-SA 4.0.
- #ANSI escape codes
- #Python
- #shutil.get_terminal_size
- #terminal line wrapping
- #textwrap.wrap



Comments