Home >Backend Development >Python Tutorial >How to Update Previous Console Lines in Python?

How to Update Previous Console Lines in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-08 14:01:02446browse

How to Update Previous Console Lines in Python?

Rewriting Multiple Lines in the Console

Question:

Is it possible to edit previous lines printed in the console and rewrite multiple lines, similar to updating a text-based RPG or a progress bar?

Answer:

Unix

Utilize the curses module for this functionality.

Windows

Consider the following options:

  • PDCurses: https://www.lfd.uci.edu/~gohlke/pythonlibs/
  • Console (as recommended in the linked HOWTO)
  • wconio: http://newcenturycomputers.net/projects/wconio.html
  • win32console: http://docs.activestate.com/activepython/2.6/pywin32/win32console.html

Example using curses (Unix):

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()

The above is the detailed content of How to Update Previous Console Lines in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn