Explain Codes LogoExplain Codes Logo

Print in one line dynamically

python
dynamic-printing
cli-interfaces
progress-tracking
Anton ShumikhinbyAnton Shumikhin·Nov 23, 2024
TLDR

To dynamically update a single line in Python, use print with end='\r' and flush=True. Here's an example:

import time for i in range(10): print(f'Count: {i}', end='\r', flush=True) time.sleep(1) # Let's pretend we're doing something important for a second.

This code within the loop will output "Count: X" and refresh it every second, without adding new lines.

Beyond 'Hello World': Advanced Printing

In Python, printing doesn't limit you to basic tasks like shouting out Hello, World!. print() in Python can flex its muscles for more creative operations, bringing your command line interfaces to life.

Le Loop: On the Same Line

For instance, if your mission is to print numbers on a single line, apart from your favorite end and sep parameters, here's one way to use them:

for num in range(1, 101): print(num, end=" ", sep=" ") # Space: The final frontier.

Ctrl + Z: Overwriting Outputs

Need to keep overwriting the last output on the same line? Say no more:

from sys import stdout import time for num in range(1, 101): stdout.write(f'\r{num}') stdout.flush() # Eat your vegetables. And flush. time.sleep(0.1)

Time Travel: Controlling Output Speed

You can pull a time traveler stunt by using time.sleep() to tweak the speed at which numbers are updated, providing greater clarity:

for i in range(1, 101): print(f'\r{i:3}', end='') time.sleep(0.05) # Not the actual time. You may stay seated.

Clean Slate: Clearing the Line Properly

Oh, and meet our friend, the ANSI escape code "\033[K". This buddy can clear the line before printing the next number, making your output look neater:

for i in range(1, 101): print(f'\r{i:<3}\033[K', end='') # Like cleaning your room, but less annoying. time.sleep(0.05)

And once your program execution is finished, don't forget to politely introduce the cursor to the next line:

import sys # After your loop ends print('', end='\n') sys.stdout.flush() # Because hygiene matters.

Coding the Codex: Encapsulating logic

For the sake of code decency, consider creating a class or method to encapsulate the dynamic printing logic. Maintainability matters!

class DynamicPrinter: @staticmethod def update_line(output): print(f'\r{output}\033[K', end='', flush=True) # It's like updating your status, but nerdy.

Now you can call DynamicPrinter.update_line() to refresh your output in a line.

Finer Points: Advanced and Interactive Outputs

Dynamic printing is more than overwriting a line. It's a door to colorful CLI applications with real-time updates, progress tracking and more.

Libraries for Fancy Printing

Libraries like tqdm and rich are your best friends for implementing progress bars and rich styled terminal output:

from tqdm import tqdm import time for _ in tqdm(range(10)): time.sleep(0.5) # Your computer is also dozing off during this nap.

Text User Interfaces with Curses

With tools like curses, you can create text-based user interfaces and make your printer dance 💃:

import curses def main(stdscr): curses.curs_set(0) stdscr.addstr("Dynamic line: ") for i in range(100): stdscr.addstr(f'\rDynamic line: {i}') stdscr.refresh() # Keeps the screen fresh. No deodorant needed. time.sleep(0.1) stdscr.addstr("\nFinished!") stdscr.refresh() # Now the screen smells nice. stdscr.getch() curses.wrapper(main)