RobertEagle RobertEagle - 1 year ago 59
Python Question

Rewriting on a specific line while other lines behave normaly

I have a python program with which I have to update the last line of a terminal while on the rest of them I print data as if the last line is non-existent. Here's an example. Suppose we have this (pseudo)code:

1. print("test1")
2. updateLastLine("79 percent")
3. print("test2")
4. updateLastLine("80 percent")

wheres on the terminal the data would look like:

the first 2 lines of code:

79 percent

the next 2 lines of code added:

80 percent

How do I implement such a solution in python? Also, how would I capture input from keyboard from the updating line? It may help to know that the only place I capture input is from the updating line. Is there any library to do this?

A close example would be the
sudo apt-get update
command which behaves similarly.

Answer Source
import shutil

class Printer(object):
    def __init__(self):
        self.last_line = ''

    def print(self, line):
        (w, h) = shutil.get_terminal_size()
        print(' '*(w-1), end='\r')

    def update_last_line(self, line):
        print(line, end=len(self.last_line) * ' ' + '\r')
        self.last_line = line

    def read_last_line(self, line):
        response = input(line)
        print('\033[{}C\033[1A'.format(len(line) + len(response)), end = '\r')
        return response

if __name__ == '__main__':
    p = Printer()
    p.update_last_line("79 percent")
    p.update_last_line("80 percent")
    response = p.read_last_line("age = ")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download