To completely clear a line when using print(end='\r'), you need to overwrite the entire previous line with spaces or use ANSI escape codes. Here are the two best approaches:
Method 1: Overwrite with Spaces
import time
# Example of a progress counter
for i in range(1, 101):
# Create a message
message = f"Processing: {i}% complete"
# Print the message, then overwrite with spaces, then return to start
print(message + " " * 20, end='\r')
# Simulate work
time.sleep(0.1)
# Print a newline at the end so your next print doesn't start on the same line
print()
The key part is " " * 20 which adds 20 spaces after your message to overwrite any previous longer text. You need to ensure you add enough spaces to cover the longest possible message.
Method 2: ANSI Escape Codes (Better Solution)
ANSI escape codes give you more control and are more reliable:
import time
# Example of a progress counter
for i in range(1, 101):
# Create a message
message = f"Processing: {i}% complete"
# Clear the entire line and return cursor to beginning
print("\033[K" + message, end='\r')
# Simulate work
time.sleep(0.1)
# Print a newline at the end
print()
The \033[K is an ANSI escape code that clears from the cursor position to the end of the line. This is more reliable than padding with spaces because it works regardless of the previous line's length.
Method 3: Using the shutil Module (Most Reliable)
This approach automatically adapts to your terminal width:
import time
import shutil
# Get terminal width
terminal_width = shutil.get_terminal_size().columns
for i in range(1, 101):
# Create a message
message = f"Processing: {i}% complete"
# Clear the entire line by printing spaces, then return to start
print(" " * terminal_width, end='\r')
print(message, end='\r')
# Simulate work
time.sleep(0.1)
print()
Bonus: Progress Bar Example
Here's a more complete example showing a progress bar:
import time
import shutil
def progress_bar(iteration, total, prefix='', suffix='', length=50, fill='█'):
"""
Call in a loop to create a terminal progress bar
"""
terminal_width = shutil.get_terminal_size().columns
percent = f"{100 * (iteration / float(total)):.1f}"
filled_length = int(length * iteration // total)
bar = fill * filled_length + '-' * (length - filled_length)
# Create the progress bar line
line = f'\r{prefix} |{bar}| {percent}% {suffix}'
# Clear the line and print the progress bar
print("\033[K" + line, end='\r')
# Print a newline when complete
if iteration == total:
print()
# Example usage
total = 100
for i in range(total + 1):
progress_bar(i, total, prefix='Progress:', suffix='Complete', length=50)
time.sleep(0.05) # Simulate work
This will display a nice progress bar that updates in place and automatically clears the line each time.
Would you like me to explain any of these approaches in more detail?