Python scripts have become popular in today’s software development. When working with command line applications or scripts in Python it’s often needed to display output in a structured manner. When we output something in Python it just gets appends the output to the existing output in the console which makes it challenging to keep track of the information displayed.

With a few techniques, we can make a new output display in the same place on the console which provides a more user-friendly experience. In this article, we will write a simple Python program to show a progress bar whose values get updated on the same line.

Using Carriage return character:

The \r the character which is also known as carriage return moves the cursor back to the beginning of the current line without advancing to the next line.

It is the most commonly used technique to write output in the same place on the console. Following is an example of how to use carriage return to write output on the same line.

import time

for i in range(10):
    print("Progress: {}/10".format(i + 1), end='\r')
    time.sleep(1)

Using curses library:

If you want a more advanced way of controlling the console output, you can use the curses library in Python. Using curses we perform several operations such as moving the cursor, scrolling the screen and erasing areas. This provides a terminal-independent way to create text-based user interfaces. Following is an example:

import curses
import time

def main(stdscr):
    for i in range(10):
        stdscr.addstr(0, 0, "Progress: {}/10".format(i + 1))
        stdscr.refresh()
        time.sleep(1)

curses.wrapper(main)

Explanation:

In the above example, Using the stdscr.addstr() we can write the output at the specified position on the screen. In the above example, we are writing at (0,0). The stdscr.refresh() call updates the screen.

Categorized in:

Tagged in: