In this video, I’ll show you how to generate Python code using the large language model ChatGPT to implement a progress bar in the command line. No complex programming knowledge required—just follow the steps to accomplish the task easily.
1. Video.
2. Source Code.
2.1 Use tqdm Library.
Below is a Python script that demonstrates how to implement a progress bar in the command line. This script uses the `tqdm` library, which is a popular and easy-to-use library for creating progress bars in Python.
First, you need to install the `tqdm` library if you haven’t already:
pip install tqdm
Now, here is a Python script that uses `tqdm` to show a progress bar:
import time from tqdm import tqdm # Number of iterations num_iterations = 100 # Create a progress bar with tqdm for i in tqdm(range(num_iterations), desc="Processing"): # Simulate some work with a sleep time.sleep(0.1) print("Processing complete!")
This script does the following:
1. Imports the necessary modules: `time` for simulating work and `tqdm` for the progress bar.
2. Defines the number of iterations for the progress bar.
3. Uses a for loop to iterate over a range of `num_iterations`.
4. Inside the loop, it updates the progress bar and simulates work by sleeping for 0.1 seconds.
5. Prints a completion message once the loop is finished.
To run this script, simply save it to a file (e.g., `progress_bar.py`) and execute it using Python:
python progress_bar.py
This will display a progress bar in the command line that updates with each iteration.
2.2 Use sys & time Library.
A progress bar is a useful feature to show the progress of a long-running operation. Below is a Python script that demonstrates how to implement a simple command line progress bar. This example uses the `sys` and `time` modules to update the progress bar in place.
Here’s the script:
import sys import time def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=50, fill='█', print_end="\r"): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : positive number of decimals in percent complete (Int) length - Optional : character length of bar (Int) fill - Optional : bar fill character (Str) print_end - Optional : end character (e.g. "\r", "\r\n") (Str) """ percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total))) filled_length = int(length * iteration // total) bar = fill * filled_length + '-' * (length - filled_length) print(f'\r{prefix} |{bar}| {percent}% {suffix}', end=print_end) # Print New Line on Complete if iteration == total: print() # Example Usage if __name__ == "__main__": items = list(range(0, 100)) total_items = len(items) print_progress_bar(0, total_items, prefix='Progress:', suffix='Complete', length=50) for i, item in enumerate(items): # Simulate some work time.sleep(0.1) # Update Progress Bar print_progress_bar(i + 1, total_items, prefix='Progress:', suffix='Complete', length=50)
Explanation
1. Function Definition: `print_progress_bar` function takes several parameters:
– `iteration`: Current iteration (int).
– `total`: Total iterations (int).
– `prefix`: Prefix string (str).
– `suffix`: Suffix string (str).
– `decimals`: Number of decimal places for percentage (int).
– `length`: Character length of the progress bar (int).
– `fill`: Bar fill character (str).
– `print_end`: End character (str), typically “\r” or “\r\n”.
2. Percent Calculation: Calculates the percentage of completion.
3. Bar Construction: Constructs the bar with the fill character and ‘-‘ for the remaining part.
4. Print Bar: Prints the bar and the percentage, updating in place.
5. New Line on Complete: Prints a new line once the task is complete.
6. Example Usage: Demonstrates how to use the `print_progress_bar` function within a loop to simulate a task progressing.
This script will display a progress bar in the command line that updates as the loop progresses. Adjust the `time.sleep(0.1)` to simulate work being done for each iteration.