Home >Backend Development >Python Tutorial >How to Create a Customizable Text Progress Bar in Your Terminal Using Python?
Many terminal-based applications require a way to visualize progress. In this article, we will explore how to create a progress bar in a terminal using block characters while preserving prior output.
The following code provides a customizable progress bar that can be used with any Python 3 application:
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'): percent = ("{0:.{0}f}".format(decimals)).format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print(f'\r{prefix} |{bar}| {percent}% {suffix}', end=printEnd) # Print new line on completion if iteration == total: print()
For convenience, the following code provides a single-call version of the above progress bar:
def progressBar(iterable, prefix='', suffix='', decimals=1, length=100, fill='█', printEnd='\r'): total = len(iterable) # Progress bar printing function def printProgressBar(iteration): percent = ("{0:.{0}f}".format(decimals)).format(100 * (iteration / float(total))) filledLength = int(length * iteration // total) bar = fill * filledLength + '-' * (length - filledLength) print(f'\r{prefix} |{bar}| {percent}% {suffix}', end=printEnd) # Initial call printProgressBar(0) # Update progress bar for i, item in enumerate(iterable): yield item printProgressBar(i + 1) # Print new line on completion print()
The following code shows how to use the progress bar:
import time # List of items items = list(range(0, 57)) # Progress bar usage for item in progressBar(items, prefix='Progress:', suffix='Complete', length=50): # Do stuff... time.sleep(0.1)
These code snippets provide a versatile and easy-to-use progress bar solution that can enhance the user experience of any terminal-based application.
The above is the detailed content of How to Create a Customizable Text Progress Bar in Your Terminal Using Python?. For more information, please follow other related articles on the PHP Chinese website!