Python print on lines that are not visible anymore on the terminal with ANSI escape codes

118 views Asked by At

I try to replace the text printed on a given line by another. For that, I have been using ANSI escape codes. My problem is when the line to be replaced is not visible on the screen anymore (but still visible by scrolling up the window) I don't seem to be able to modify it anymore. Here is a simple standalone example of my problem :

import os

nb_lines_term = int(os.popen('stty size', 'r').read().split()[0])

tot_lines = nb_lines_term + 5
for i in range(tot_lines):
    print 'line', tot_lines - i

line_to_replace = nb_lines_term + 2
new_str = "\033[F" * line_to_replace  # go u
new_str += 'replacing line ' + str(line_to_replace)
new_str += "\033[E" * (line_to_replace - 1)  # go back down
print new_str

Is there a way to access the line still? by ANSI escape codes or any other method?

1

There are 1 answers

1
Thomas Dickey On BEST ANSWER

short: no

longer: by convention, once data has left the visible screen, terminal emulators may leave the data which has scrolled out of sight in read-only scrollback area.

That reflects the adaptation of hardware terminals to emulators. Very few hardware terminals provided for panning around in a wider region (and few provided any way to see data which had scrolled out of sight). So what was standardized did not provide for this sort of feature, because the existing control sequences dealt with the visible screen.

There are of course exceptions (Hewlett Packard made some interesting terminals, for which you cannot find an emulator). xterm (and some that copied the feature) allows you to clear the scrollback. But you're unlikely to find something that lets you (under program control) scroll back and modify the scrollback area.

Application developers manage the visible display, writing lines on that using their own data rather than relying on the terminal to provide that out-of-sight information.