JRJurman JRJurman - 1 year ago 127
Python Question

Python - Rewrite multiple lines in the Console

I know it is possible to consistently rewrite the last line displayed in the terminal with "\r", but I am having trouble figuring out if there is a way to go back and edit previous lines printed in the console.

What I would like to do is reprint multiple lines for a text-based RPG, however a friend was also wondering about this for an application which had one line dedicated to a progress bar, and another describing the download.

i.e. the console would print:

Moving file: NameOfFile.txt

Total Progress: [######## ] 40%

and then update appropriately (to both lines) as the program was running.

Answer Source

On Unix, use the curses module.

On Windows, there are several options:

Simple example using curses (I am a total curses n00b):

import curses
import time

def report_progress(filename, progress):
    """progress: 0-10"""
    stdscr.addstr(0, 0, "Moving file: {0}".format(filename))
    stdscr.addstr(1, 0, "Total progress: [{1:10}] {0}%".format(progress * 10, "#" * progress))

if __name__ == "__main__":
    stdscr = curses.initscr()

        for i in range(10):
            report_progress("file_{0}.txt".format(i), i+1)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download