Clearing the last line in the terminal when text wraps around
Question:
In my python program I want to print progress over a very long loop. I want to output specific information like percent complete etc…, but I don’t want all this output to take up the whole screen.
Ideally, I want to to print a progress line. Something like
train 53/56...x6 │ loss:1.356 │ miou:0.276 │ rate=3.13 Hz, eta=0:00:01, total=0:00:17, wall=19:48 EST
Then, when the next line prints, I want to simply overwrite this line.
Currently I can do this by simply printing carriage return 'r'
before I print my message. This returns the cursor to the beginning of the line and then overwrites the line. Exactly what I want.
The issue is when the terminal is too small for the entire line to fit, the line wraps around and the carriage return brings me to the beginning of the wrapped line, not the absolute beginning of the line.
Is there a way that I can bring the cursor all the way back to the beginning of the correct line?
Answers:
You can use ANSI escape sequences for cursor movement, most notably:
- Position the Cursor:
In my python program I want to print progress over a very long loop. I want to output specific information like percent complete etc…, but I don’t want all this output to take up the whole screen.
Ideally, I want to to print a progress line. Something like
train 53/56...x6 │ loss:1.356 │ miou:0.276 │ rate=3.13 Hz, eta=0:00:01, total=0:00:17, wall=19:48 EST
Then, when the next line prints, I want to simply overwrite this line.
Currently I can do this by simply printing carriage return 'r'
before I print my message. This returns the cursor to the beginning of the line and then overwrites the line. Exactly what I want.
The issue is when the terminal is too small for the entire line to fit, the line wraps around and the carriage return brings me to the beginning of the wrapped line, not the absolute beginning of the line.
Is there a way that I can bring the cursor all the way back to the beginning of the correct line?
You can use ANSI escape sequences for cursor movement, most notably:
- Position the Cursor: