logo

How to Replace Existing Output with New Output in Python and Display Progress 📂Programing

How to Replace Existing Output with New Output in Python and Display Progress

English Translation

When you want to find out the progress while the code is running, using the print() function, it will be printed like this:

for i in range(1,6):
    print(f"진행 경과[{i}/5]")

3507_one_line_1.webp

At this time, you can add \r in front of the string and use the option end="" for print(). \r moves the cursor to the beginning, and end="" turns off the default newline option of print().

for i in range(1,6):
    print(f"\r진행 경과[{i}/5]", end="")

3507_one_line_2.webp

If you want to display the progress over multiple lines, you can easily implement this using the reprint library. As shown in the example code below, results are displayed according to output_lines[i] within a with statement.

Installation

Install via the following command line in the cmd window.

>>>pip install reprint

Code

from reprint import output

with output(initial_len=3, interval=0) as output_lines:
    for i in range(1,6):
        output_lines[0] = f"진행 경과[{i}/5]"
        for j in range(10):
            output_lines[1] = f"j = {j}"
            output_lines[2] = f"j^2 = {j**2}"

3507_multilines.webp

Environment

  • OS: Windows11
  • Version: Python v3.9.13, reprint==0.6.0