Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 307
JRJurman Avatar asked Jul 27 '11 06:07

JRJurman


People also ask

How do you write multiple lines in python console?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.


1 Answers

On Unix, use the curses module.

On Windows, there are several options:

  • PDCurses: http://www.lfd.uci.edu/~gohlke/pythonlibs/
  • The HOWTO linked above recommends the Console module
  • http://newcenturycomputers.net/projects/wconio.html
  • http://docs.activestate.com/activepython/2.6/pywin32/win32console.html

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))     stdscr.refresh()  if __name__ == "__main__":     stdscr = curses.initscr()     curses.noecho()     curses.cbreak()      try:         for i in range(10):             report_progress("file_{0}.txt".format(i), i+1)             time.sleep(0.5)     finally:         curses.echo()         curses.nocbreak()         curses.endwin() 
like image 164
codeape Avatar answered Sep 19 '22 13:09

codeape